<?php
namespace app\index\controller;

use app\index\model\FlowLogModel;
use app\index\model\MainBasalListModel;
use app\index\model\MainBasalModel;
use app\index\model\MainBaseCaiModel;
use app\index\model\MainBaseFenModel;
use app\index\model\MainBaseJiModel;
use app\index\model\MainBaseRenModel;
use app\index\model\MainEnginModel;
use app\index\model\MainHuishuModel;
use app\index\model\MainHuizaoModel;
use app\index\model\MainHuiziModel;
use app\index\model\MainJianEnginChuiModel;
use app\index\model\MainJianEnginCuoModel;
use app\index\model\MainJianEnginGongModel;
use app\index\model\MainJianEnginGuanModel;
use app\index\model\MainJianEnginYuoneModel;
use app\index\model\MainJianEnginYutwoModel;
use app\index\model\MainMarkCaiListModel;
use app\index\model\MainMarkCaiModel;
use app\index\model\MainMarkFenListModel;
use app\index\model\MainMarkFenModel;
use app\index\model\MainMarkJiListModel;
use app\index\model\MainMarkJiModel;
use app\index\model\MainMarkModel;
use app\index\model\MainMarkRenListModel;
use app\index\model\MainMarkRenModel;
use app\index\model\MainMarkTypeModel;
use app\index\model\MainOptionModel;
use app\index\model\MainQingListModel;
use app\index\model\MainQingModel;
use app\index\model\MainWeekLeaseModel;
use app\index\model\MainWeekStuffModel;
use app\index\model\UserModel;
use app\index\service\MainService;
use app\index\service\MenuService;
use app\index\service\OptService;
use app\index\service\UserService;
use think\Db;
use think\Request;

class Main extends Common
{
    //项目信息
    public function list_main_engin(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }


        $data['data'] = MainEnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('main_engin', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('main_engin');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_main_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入工程名称');
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                $id = MainEnginModel::insertGetId($param);
                (new OptService())->relation_file($files,'main_engin',$id);

                (new MainService())->create_dea_marktype($id);
                (new MainService())->create_huishu($id);

                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'main_engin', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'main_engin', $id, '成本编制项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['files'] = (new OptService())->get_file('main_engin');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function del_main_engin(Request $request){
        $param = $request->post();
        $data = MainEnginModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            MainEnginModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);

            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'main_engin', $data['id'], '成本编制项目');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_main_engin(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = MainEnginModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }
        $data['files'] = (new OptService())->get_file('main_engin', $data['data']['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }

    //工程量清单
    public function list_qing(Request $request){
        $param = $request->post();
        $where[] = ['comid','=',$this->userinfo['comid']];
        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }
        $list = MainQingModel::where($where)->order('sort ASC,id ASC')->select()->toArray();
        foreach ($list as &$item){
            $item['nums'] = MainQingListModel::where(['qingid'=>$item['id']])->count();
        }
        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_qingnav(Request $request){
        $param = $request->post();
        $where= [];
        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['encode|enname|enfeat|enunit|enword','like','%'.$param['keyword'].'%'];
        }

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }else{
            $where[] = ['enginid','=',0];
        }
        if(isset($param['qingid']) && !empty($param['qingid'])){
            $where[] = ['qingid','=',$param['qingid']];
        }
        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'qing');


        $list = MainQingListModel::field('fenname as enname')->where($where)->group('fenname')->order('id ASC')->select()->toArray();
        foreach ($list as &$item){
            $item['enword'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('enword');
            $item['renprice'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('renprice');
            $item['caiprice'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('caiprice');
            $item['jiprice'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('jiprice');
            $item['fenprice'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('fenprice');
            $item['price'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('price');
            $item['money'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('money');
            $item['renfee_cur'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('renfee_cur');
            $item['caifee_cur'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('caifee_cur');
            $item['jifee_cur'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('jifee_cur');
            $item['fenfee_cur'] = MainQingListModel::where($where)->where('fenname',$item['enname'])->sum('fenfee_cur');

            $item['renprice'] = number_format($item['renprice'],2);
            $item['caiprice'] = number_format($item['caiprice'],2);
            $item['jiprice'] = number_format($item['jiprice'],2);
            $item['fenprice'] = number_format($item['fenprice'],2);
            $item['price'] = number_format($item['price'],2);
            $item['money'] = number_format($item['money'],2);
            $item['renfee_cur'] = number_format($item['renfee_cur'],2);
            $item['caifee_cur'] = number_format($item['caifee_cur'],2);
            $item['jifee_cur'] = number_format($item['jifee_cur'],2);
            $item['fenfee_cur'] = number_format($item['fenfee_cur'],2);

            $item['iszi'] = 1;
        }
        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_qinglist(Request $request){
        $param = $request->post();
        $where= [];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }else{
            $where[] = ['enginid','=',0];
        }
        if(isset($param['qingid']) && !empty($param['qingid'])){
            $where[] = ['qingid','=',$param['qingid']];
        }
        $fenname = '';
        if(isset($param['fenname']) && !empty($param['fenname'])){
            $where[] = ['fenname','=',$param['fenname']];
            $fenname = $param['fenname'];
        }
        $ziname = '';
        if(isset($param['ziname']) && !empty($param['ziname'])){
            $ziname = $param['ziname'];
        }


        $data = [];
        $zhijie = 0;

        if(empty($ziname)){
            $ziArr = MainQingListModel::field('ziname as enname')->where($where)
                ->where(['fenname'=>$fenname])->group('ziname')->order('id ASC')->select()->toArray();
            if(!empty($ziArr[0]['enname'])){
                foreach ($ziArr as &$vvv){
                    $vvv['fenname'] = $fenname;
                    $vvv['iszi'] = 1;
                }
                $data['data'] = $ziArr;
            }else{
                $zhijie = 1;
            }
        }else{
            $zhijie = 1;
        }

        if($zhijie > 0){
            $arr = MainQingListModel::where($where)->where(['fenname'=>$fenname,'ziname'=>$ziname])->order('id ASC')->select()->toArray();
            foreach ($arr as &$v){
                $v['iszi'] = 0;
                if(isset($param['list']) && !empty($param['list'])){
                    foreach ($param['list'] as $vv){
                        if($v['id'] == $vv['id']){
                            $v['LAY_CHECKED'] = true;
                            $v['han'] = $vv['han'];
                            break;
                        }
                    }
                }
            }
            $data['data'] = $arr;
        }

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_qing(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();


            $list = array_filter($param['list']);
            unset($param['list']);
            unset($param['token']);
            if(count($list) < 1){
                return outputJson(4009, "请上传清单明细");
            }


            $exist = MainqingModel::where(['enginid'=>$param['enginid'],'qingname'=>$param['qingname']])->find();
            if($exist){
                $param['qingname'] .= '（2）';
            }


            Db::startTrans();
            try {
                $qingid = MainQingModel::insertGetId($param);
                foreach ($list as $item){
                    $item['qingid'] = $qingid;
                    $item['enginid'] = $param['enginid'];
                    MainQingListModel::insert($item);
                }

                (new MainService())->update_at_main($param['enginid'], 'qing');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000, lang('code_2000'));
        } else {
            return outputJson(2000, lang('code_2000'));
        }
    }
    public function guan_qing(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            unset($param['list']);

            $delArr = [];
            $oldList = MainQingModel::where(['enginid'=>$param['enginid']])->select()->toArray();
            foreach ($oldList as $v){
                $exist = false;
                foreach ($list as $vvv){
                    if($v['id'] == $vvv['id']){
                        $exist = true;
                    }
                }
                if(!$exist){
                    $delArr[] = $v['id'];
                }
            }




            Db::startTrans();
            try {
                foreach ($delArr as $mmm){
                    MainQingModel::where(['id'=>$mmm])->delete();
                    MainqinglistModel::where(['qingid'=>$mmm])->delete();
                }

                foreach ($list as $k=>$item){
                    MainQingModel::where(['id'=>$item['id']])->update(['sort'=>$k,'qingname'=>$item['qingname']]);
                }
                (new MainService())->update_at_main($param['enginid'], 'qing');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->get('enginid', 0, 'int');
            $data = MainQingModel::where(['enginid'=>$enginid])->order('sort ASC')->select()->toArray();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function export_qing(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $engininfo = MainEnginModel::where(['id'=>$param['id']])->find();

            $excelFileName = $engininfo['name'].'工程量清单'.date("Y年m月d日");
            $sheetTitle = [];
            $fieldArr = [
                'encode'=>'项目编码',
                'enname'=>'工程名称',
                'enfeat'=>'项目特征描述',
                'enunit'=>'计量单位',
                'enword'=>'工程量',
                'renprice'=>'人工费(元)',
                'caiprice'=>'材料费(元)',
                'jiprice'=>'机械费(元)',
                'fenprice'=>'专业分包(元)',
                'price'=>'综合成本单价(元)',
                'money'=>'综合成本合(元)',
                'renfee_cur'=>'人工费合计(元)',
                'caifee_cur'=>'材料费合计(元)',
                'jifee_cur'=>'机械费合计(元)',
                'fenfee_cur'=>'专业分包合计(元)',
            ];
            $excelFieldsZHCN = [];
            $list = [];

            $data = MainQingModel::where(['enginid'=>$param['id']])->select()->toArray();
            foreach ($data as $kkk=>$item){
                $excelFieldsZHCN[] = $fieldArr;
                $sheetTitle[] = $item['qingname'];

                $fenname = '';
                $qinglist = [];
                $ziHang = 0;
                $zong = [
                    'enname' => '合计',
                    'fee_cai' => 0,
                    'fee_ren' => 0,
                    'fee_zhuan' => 0,
                    'fee_ji' => 0,
                    'fee_zong' => 0,
                ];
                $qingarr = MainQingListModel::where(['enginid'=>$param['id'],'qingid'=>$item['id']])->select()->toArray();

                foreach ($qingarr as $k=>$v){
                    if($v['fenname'] != $fenname){
                        $qinglist[] = ['enname'=>$v['fenname']];
                        $ziHang = count($qinglist) - 1;
                        $fenname = $v['fenname'];

                        $qinglist[$ziHang]['renprice'] = 0;
                        $qinglist[$ziHang]['caiprice'] = 0;
                        $qinglist[$ziHang]['jiprice'] = 0;
                        $qinglist[$ziHang]['fenprice'] = 0;
                        $qinglist[$ziHang]['price'] = 0;
                        $qinglist[$ziHang]['money'] = 0;
                        $qinglist[$ziHang]['renfee_cur'] = 0;
                        $qinglist[$ziHang]['caifee_cur'] = 0;
                        $qinglist[$ziHang]['jifee_cur'] = 0;
                        $qinglist[$ziHang]['fenfee_cur'] = 0;
                    }


                    $qinglist[$ziHang]['renprice'] += $v['renprice'];
                    $qinglist[$ziHang]['caiprice'] += $v['caiprice'];
                    $qinglist[$ziHang]['jiprice'] += $v['jiprice'];
                    $qinglist[$ziHang]['fenprice'] += $v['fenprice'];
                    $qinglist[$ziHang]['price'] += $v['price'];
                    $qinglist[$ziHang]['money'] += $v['money'];
                    $qinglist[$ziHang]['renfee_cur'] += $v['renfee_cur'];
                    $qinglist[$ziHang]['caifee_cur'] += $v['caifee_cur'];
                    $qinglist[$ziHang]['jifee_cur'] += $v['jifee_cur'];
                    $qinglist[$ziHang]['fenfee_cur'] += $v['fenfee_cur'];

                    $v['enfeat'] = str_replace(  '<br/>',"\n", $v['enfeat']);
                    $qinglist[] = $v;
                }
                $qinglist[] = $zong;

                $list[] = $qinglist;
            }


            deldir('./mainexcel/');
            (new MainService())->exportExcels($list, $excelFieldsZHCN, $excelFileName, $sheetTitle);
            return outputJson(2000,lang('code_2000'), 'mainexcel/'.$excelFileName.'.xls');
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function addhang_qing(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['enname'])){
                return outputJson(4000, '请输入工程名称');
            }
            if(empty($param['enunit'])){
                return outputJson(4000, '请输入计量单位');
            }
            if($param['enword'] == ''){
                return outputJson(4000, '请输入工程量');
            }

            $old = MainQingListModel::where(['id'=>$param['id']])->find();

            $param['qingid'] = $old['qingid'];
            $param['enginid'] = $old['enginid'];
            $param['fenname'] = $old['fenname'];
            $param['ziname'] = $old['ziname'];

            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['id']);
            unset($param['token']);

            Db::startTrans();
            try {
                MainQingListModel::insertGetId($param);
                (new MainService())->update_at_main($old['enginid'], 'qing');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            return outputJson(2000,lang('code_2000'));
        }
    }
    public function edithang_qing(Request $request){
        if($request->isPost()){
            $param = $request->post();

//            if(empty($param['enname'])){
//                return outputJson(4000, '请输入工程名称');
//            }
//            if(empty($param['enunit'])){
//                return outputJson(4000, '请输入计量单位');
//            }
            if($param['enword'] == ''){
                return outputJson(4000, '请输入工程量');
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                MainQingListModel::where(['id'=>$param['id']])->update($param);
                $qingInfo = MainQingListModel::where(['id'=>$param['id']])->find();

                (new MainService())->update_at_main($qingInfo['enginid'], 'qing');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = MainQingListModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function delhang_qing(Request $request){
        $param = $request->post();
        $data = MainQingListModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            MainQingListModel::where(['id'=>$data['id']])->delete();
            $qingInfo = MainQingListModel::where(['id'=>$param['id']])->find();

            (new MainService())->update_at_main($qingInfo['enginid'], 'qing');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    //工程概况
    public function edit_gai(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入工程名称');
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);

            $list = array_filter($param['list']);
            unset($param['list']);


            Db::startTrans();
            try {
                MainEnginModel::where(['id'=>$param['id']])->update($param);
                foreach ($list as $v){
                    MainQingModel::update($v);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            $data['edittitss'] = (new MainService())->get_maineditshi($param['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = MainEnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $qing = MainQingModel::where(['enginid'=>$id])->select()->toArray();
            $data['qing'] = $qing;
            $data['edittitss'] = (new MainService())->get_maineditshi($id);
            $data['areas'] = (new OptService())->get_city_cader();
            $data['xiangtype'] = (new MainService())->get_base_info('xiangtype');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    //选择基准费用
    public function check_mark(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['deleted_user','=', 0];
        $where[] = ['comid','=',$this->userinfo['comid']];
        $where[] = ['enginid','=',$param['enginid']];
        $where[] = ['type','=', $param['type']];

        $data['basetypearr'] = MainMarkTypeModel::where(['enginid'=>$param['enginid'],'type'=>$param['type']])->order('id ASC')->column('name');
        $data['basetype'] = isset($param['basetype']) ? $param['basetype'] : '';
        if(!in_array($data['basetype'],$data['basetypearr'])){
            $param['basetype'] = '';
            $data['basetype'] = '';
        }

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['name|guige|valunit|explain','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['basetype']) && !empty($param['basetype'])){
            $where[] = ['basetype','=', $param['basetype']];
        }

        $paramList = MainMarkModel::where($where)->select()->toArray();


        $sstypeArr = [];
        $list = [];
        foreach ($data['basetypearr'] as $typename){
            $sstypeArr[] = $typename;
            foreach ($paramList as $k=>$v){
                if($v['basetype'] == $typename){
                    $list[] = $v;
                }
            }
        }
        foreach ($paramList as $k=>$v){
            if(!in_array($v['basetype'], $sstypeArr)){
                $list[] = $v;
            }
        }


        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }

    //基底清单
    public function add_basal(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            $list = MainQingListModel::field('enginid,fenname,encode,enname,enfeat,enunit,sum(enword) as enword')
                ->where(['enginid'=>$param['enginid']])
                ->group('fenname,enname,enfeat,enunit')
                ->order('id ASC')
                ->select()->toArray();

            Db::startTrans();
            try {
                MainBasalModel::where(['enginid'=>$param['enginid']])->update(['isexist'=>0]);
                foreach ($list as $vvv){
                    $upd = MainBasalModel::where([
                        'enginid'=>$vvv['enginid'],
                        'fenname'=>$vvv['fenname'],
                        'enname'=>$vvv['enname'],
                        'enfeat'=>$vvv['enfeat'],
                        'enunit'=>$vvv['enunit'],
                    ])->update(['isexist'=>1,'enword'=>$vvv['enword']]);
                    if($upd > 0){
                    }else{
                        unset($vvv['id']);
                        $vvv['isexist'] = 1;
                        MainBasalModel::insert($vvv);
                    }
                }

                // 查询isexist = 1的数据，并且查询相关联的清单明细数据，存在则处理统计数据和明细
                $basal = MainBasalModel::where(['enginid'=>$param['enginid'],'isexist'=>1])->select()->toArray();
                foreach ($basal as $v){
                    // 存在基底清单明细
                    $list = MainBasalListModel::where(['basalid'=>$v['id']])->select()->toArray();
                    if($list){
                        $renfee = $renprice = $caifee = $caiprice = $jifee = $jiprice = $fenfee = $fenprice = $money = $price = 0;
                        foreach ($list as $item){
                            if($item['type'] == 1){ # 人工费
                                $renprice += $item['price'];
                            }else if($item['type'] == 2){ # 材料费
                                $caiprice += $item['price'];
                            }else if($item['type'] == 3){ # 机械费
                                $jiprice += $item['price'];
                            }else if($item['type'] == 4){ # 分包费
                                $fenprice += $item['price'];
                            }
                        }
                        $price = $renprice + $caiprice + $jiprice + $fenprice;
                        $renfee = round($renprice * $v['enword'],2);
                        $caifee = round($caiprice * $v['enword'],2);
                        $jifee = round($jiprice * $v['enword'],2);
                        $fenfee = round($fenprice * $v['enword'],2);
                        $money = $renfee + $caifee + $jifee + $fenfee;
                        // 处理基底清单中的统计数据
                        $basal_ins = [
                            'renfee' => $renfee,
                            'renprice' => $renprice,
                            'caifee' => $caifee,
                            'caiprice' => $caiprice,
                            'jifee' => $jifee,
                            'jiprice' => $jiprice,
                            'fenfee' => $fenfee,
                            'fenprice' => $fenprice,
                            'money' => $money,
                            'price' => $price
                        ];
                        MainBasalModel::where('id',$v['id'])->update($basal_ins);

                        // 处理工程量清单中的统计数据
                        # 查询符合条件的清单 'encode'=>$basal_data['encode'],
                        $qing_data = MainqinglistModel::where(['enginid'=>$v['enginid'],'fenname'=>$v['fenname'],
                            'enname'=>$v['enname'], 'enfeat'=>$v['enfeat'],'enunit'=>$v['enunit']])->select();
                        # 获取工程量，并计算费用
                        foreach ($qing_data as $item){
                            $ins['renprice'] = $renprice;
                            $ins['caiprice'] = $caiprice;
                            $ins['jiprice'] = $jiprice;
                            $ins['fenprice'] = $fenprice;
                            $ins['price'] = $price;
                            $ins['renfee'] = $renfee;
                            $ins['caifee'] = $caifee;
                            $ins['jifee'] = $jifee;
                            $ins['fenfee'] = $fenfee;
                            $ins['renfee_cur'] = round($renprice * $item['enword'],2);
                            $ins['caifee_cur'] = round($caiprice * $item['enword'],2);
                            $ins['jifee_cur'] = round($jiprice * $item['enword'],2);
                            $ins['fenfee_cur'] = round($fenprice * $item['enword'],2);
                            $ins['money'] = $ins['renfee_cur'] + $ins['caifee_cur'] + $ins['jifee_cur'] + $ins['fenfee_cur'];
                            MainqinglistModel::where('id',$item['id'])->update($ins);
                            unset($ins);
                        }
                    }
                }

                // 查询isexist = 0的数据
                MainBasalModel::where(['enginid'=>$param['enginid'],'isexist'=>0])->delete();


                (new MainService())->update_at_main($param['enginid'], 'basal');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000, lang('code_2000'));
        } else {
            return outputJson(2000, lang('code_2000'));
        }
    }
    public function list_basalnav(Request $request){
        $param = $request->post();
        $where= [];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }else{
            $where[] = ['enginid','=',0];
        }

        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'basal');

        $list = MainBasalModel::field('fenname as enname')->where($where)->group('fenname')->order('id ASC')->select()->toArray();
        foreach ($list as &$item){
            $item = (new MainService())->get_basal_nav_huizong($param['enginid'],$item['enname']);
        }

        $data['data'] = $list;
        $data['type'] = (new MainService())->get_main_type();


        $basetypearr = [];
        foreach ($data['type'] as $kk=>$vv){
            $basetypearr[$kk] = MainMarkTypeModel::where(['enginid'=>$param['enginid'],'type'=>$kk])->order('id ASC')
                ->field('id,name')->select()->toArray();
        }
        $data['basetypearr'] = $basetypearr;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_basallist(Request $request){
        $param = $request->post();
        $where= [];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }else{
            $where[] = ['enginid','=',0];
        }

        if(isset($param['fenname']) && !empty($param['fenname'])){
            $where[] = ['fenname','=',$param['fenname']];
        }

        // 基准费用的id
        if(isset($param['param_id']) && !empty($param['param_id'])){

            $use = MainMarkModel::where('id',$param['param_id'])->find();
            if($use){
                $wheres[] = ['type','=',$use['type']];
                $wheres[] = ['basetype','=',$use['basetype']];
                $wheres[] = ['name','=',$use['name']];
                $wheres[] = ['guige','=',$use['guige']];
                $wheres[] = ['valunit','=',$use['valunit']];
                $basalIdArr = MainBasalListModel::where($wheres)->column('basalid');
                $where[] = ['id','in',$basalIdArr];
            }
        }


        $arr = MainbasalModel::where($where)->order('encode ASC')->select()->toArray();
        foreach ($arr as &$item) {
            $main_list = MainBasalListModel::where('basalid',$item['id'])->field('no_price')->select()->toArray();
            if($main_list){
                $item['exists'] = 2;
                foreach ($main_list as $vv){
                    if($vv['no_price'] == 0){
                        $item['exists'] = 4;
                    }
                }
            }else{
                $item['exists'] = 1;
            }

        }

        $data['data'] = $arr;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_basallist(Request $request){
        if($this->request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);

            $basalinfo = MainBasalModel::where(['id'=>$param['basalid']])->find();
            $param['enword'] = $basalinfo['enword'];

            $updGengBasal = [];
            $updGengBasalParent = [];
            Db::startTrans();
            try{

                $oldBasal = MainBasalListModel::where('basalid',$param['basalid'])->select()->toArray();
                foreach ($oldBasal as $oldvv){
                    MainbasallistModel::where('id',$oldvv['id'])->delete();
                    MainMarkModel::where(['enginid'=>$oldvv['enginid'],'type'=>$oldvv['type'], 'basetype'=>$oldvv['basetype'],
                        'name'=>$oldvv['name'],'guige'=>$oldvv['guige'],'valunit'=>$oldvv['valunit'],'isyuan'=>0])->update(['isfake'=>1]);
                }

                $GengArr = [];
                foreach ($list as $newvv){
                    $newlistid = MainBasalListModel::insertGetId($newvv);

                    $isMarkInfo = MainMarkModel::where(['id' => $newvv['markid']])->find();
                    if(!$isMarkInfo) {
                        $isMarkInfo = MainMarkModel::where(['enginid'=>$newvv['enginid'],'type'=>$newvv['type'], 'basetype'=>$newvv['basetype'],
                            'name'=>$newvv['name'],'guige'=>$newvv['guige'],'valunit'=>$newvv['valunit']])->find();
                        if(!$isMarkInfo){
                            $markid = MainMarkModel::insertGetId([
                                'comid' => $this->userinfo['comid'],
                                'enginid' => $newvv['enginid'],
                                'type' => $newvv['type'],
                                'basetype' => $newvv['basetype'],
                                'name' => $newvv['name'],
                                'guige' => $newvv['guige'],
                                'valunit' => $newvv['valunit'],
                                'loss_rate' => $newvv['loss_rate'],
                                'no_price' => $newvv['no_price'],
                                'content' => $newvv['content'],
                                'content_exp' => $newvv['content_exp'],
                                'price' => $newvv['price'],
                                'created_user' => $this->userinfo['id'],
                                'created_at' => date('Y-m-d H:i:s')
                            ]);
                            $isMarkInfo = MainMarkModel::where(['id' => $markid])->find();
                        }
                    }
                    MainBasalListModel::where(['id'=>$newlistid])->update(['markid'=>$isMarkInfo['id']]);
                    MainMarkModel::where(['id'=>$isMarkInfo['id']])->update([
                        'type' => $newvv['type'],
                        'basetype' => $newvv['basetype'],
                        'name' => $newvv['name'],
                        'guige' => $newvv['guige'],
                        'valunit' => $newvv['valunit'],
                        'no_price'=>$newvv['no_price'],
                        'loss_rate'=>$newvv['loss_rate'],
                        'price'=>$newvv['price'],
                        'content'=>$newvv['content'],
                        'content_exp'=>$newvv['content_exp'],
                        'isfake'=>0
                    ]);

                    MainBasalListModel::where(['markid'=>$isMarkInfo['id'],'enginid'=>$newvv['enginid']])->update([
                        'type' => $newvv['type'],
                        'basetype' => $newvv['basetype'],
                        'name' => $newvv['name'],
                        'guige' => $newvv['guige'],
                        'valunit' => $newvv['valunit'],
                        'no_price'=>$newvv['no_price'],
                        'loss_rate'=>$newvv['loss_rate'],
                        'price'=>$newvv['price'],
                        'content'=>$newvv['content'],
                        'content_exp'=>$newvv['content_exp'],
                    ]);
                    $curGeng =  MainBasalListModel::where(['markid'=>$isMarkInfo['id'],'enginid'=>$newvv['enginid']])
                        ->group('basalid')->column('basalid');
                    $GengArr = array_unique(array_merge($GengArr, $curGeng));
                }

                $fakeArr = MainMarkModel::where(['enginid'=>$basalinfo['enginid'],'isfake'=>1])->select()->toArray();
                foreach ($fakeArr as $fakvv){
                    if( !MainBasalListModel::where(['markid'=>$fakvv['id']])->find() ){
                        MainMarkModel::where(['id'=>$fakvv['id']])->delete();
                    }
                }

                $parentFenname = [];
                foreach ($GengArr as $gengId){
                    $gengBasal = MainBasalModel::where(['id'=>$gengId])->find();
                    $gengBasalList = MainBasalListModel::where(['basalid'=>$gengId])->select()->toArray();
                    $parentFenname[] = $gengBasal['fenname'];


                    $updss['id'] = $gengId;
                    $updss['renprice'] = 0;
                    $updss['caiprice'] = 0;
                    $updss['jiprice'] = 0;
                    $updss['fenprice'] = 0;
                    foreach ($gengBasalList as $vvv){
                        if($vvv['type'] == 1) $updss['renprice'] += $vvv['price'];
                        if($vvv['type'] == 2) $updss['caiprice'] += $vvv['price'];
                        if($vvv['type'] == 3) $updss['jiprice'] += $vvv['price'];
                        if($vvv['type'] == 4) $updss['fenprice'] += $vvv['price'];
                    }
                    $updss['price'] = $updss['renprice'] + $updss['caiprice'] + $updss['jiprice'] + $updss['fenprice'];

                    $updss['renfee'] = round($updss['renprice'] * $gengBasal['enword'],2);
                    $updss['caifee'] = round($updss['caiprice'] * $gengBasal['enword'],2);
                    $updss['jifee'] = round($updss['jiprice'] * $gengBasal['enword'],2);
                    $updss['fenfee'] = round($updss['fenprice'] * $gengBasal['enword'],2);
                    $updss['money'] = $updss['renfee'] + $updss['caifee'] + $updss['jifee'] + $updss['fenfee'];
                    MainBasalModel::update($updss);
                    $updGengBasal[] = $updss;


                    //处理工程量清单数据
                    $qing_data = MainQingListModel::where(['enginid'=>$gengBasal['enginid'],'fenname'=>$gengBasal['fenname'],
                        'enname'=>$gengBasal['enname'], 'enfeat'=>$gengBasal['enfeat'],'enunit'=>$gengBasal['enunit']])->select()->toArray();
                    foreach ($qing_data as $item){
                        $item['enword'] = floatval($item['enword']);
                        $ins = [];
                        $ins['renprice'] = $updss['renprice'];
                        $ins['caiprice'] = $updss['caiprice'];
                        $ins['jiprice'] = $updss['jiprice'];
                        $ins['fenprice'] = $updss['fenprice'];
                        $ins['price'] = $updss['price'];
                        $ins['renfee_cur'] = round($updss['renprice'] * $item['enword'],2);
                        $ins['caifee_cur'] = round($updss['caiprice'] * $item['enword'],2);
                        $ins['jifee_cur'] = round($updss['jiprice'] * $item['enword'],2);
                        $ins['fenfee_cur'] = round($updss['fenprice'] * $item['enword'],2);
                        $ins['money'] = $ins['renfee_cur'] + $ins['caifee_cur'] + $ins['jifee_cur'] + $ins['fenfee_cur'];
                        MainQingListModel::where('id',$item['id'])->update($ins);
                    }
                }

                $parentFenname = array_unique($parentFenname);
                foreach ($parentFenname as $v){
                    $updGengBasalParent[] = (new MainService())->get_basal_nav_huizong($basalinfo['enginid'],$v);
                }


                (new MainService())->update_at_main($basalinfo['enginid'], 'basal');
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }

            $data['updGengBasal'] = $updGengBasal;
            $data['updGengBasalParent'] = $updGengBasalParent;
            return outputJson(2000,lang('code_2000'),$data);
        }else{
            $id = $request->get('id', 0, 'int');
            $data['data'] = MainBasalModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = MainBasalListModel::where(['basalid'=>$id])->select()->toArray();
            $data['list'] = $list;

            $data['tit'] = (new MainService())->get_maineditshi($data['data']['enginid'],'basal');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function tplex_basallist(Request $request){
        if($this->request->isPost()){
            $param = $request->post();
            $yuanlist = array_filter($param['yuanlist']);
            $tonglist = array_filter($param['tonglist']);

            $basalinfo = MainBasalModel::where(['id'=>$param['id']])->find();

            Db::startTrans();
            try{

                foreach ($tonglist as $tongvv){
                    // 1-覆盖  2-附加
                    if($param['types'] == 1){
                        MainBasalListModel::where(['basalid'=>$tongvv['id']])->delete();
                        foreach ($yuanlist as $yuanvv){
                            MainBasalListModel::insert([
                                'enginid' => $yuanvv['enginid'],
                                'basalid' => $tongvv['id'],
                                'markid' => $yuanvv['markid'],
                                'type' => $yuanvv['type'],
                                'basetype' => $yuanvv['basetype'],
                                'name' => $yuanvv['name'],
                                'guige' => $yuanvv['guige'],
                                'valunit' => $yuanvv['valunit'],
                                'content' => $yuanvv['content'],
                                'content_exp' => $yuanvv['content_exp'],
                                'loss_rate' => $yuanvv['loss_rate'],
                                'no_price' => $yuanvv['no_price'],
                                'price' => $yuanvv['price'],
                                'explain' => $yuanvv['explain'],
                            ]);
                        }
                    }else{
                        foreach ($yuanlist as $yuanvv){
                            $exist = MainBasalListModel::where(['enginid'=>$yuanvv['enginid'],'type'=>$yuanvv['type'],'basalid'=>$tongvv['id'],
                                'basetype'=>$yuanvv['basetype'], 'name'=>$yuanvv['name'],'guige'=>$yuanvv['guige'],'valunit'=>$yuanvv['valunit']])->find();
                            if(!$exist){
                                MainBasalListModel::insert([
                                    'enginid' => $yuanvv['enginid'],
                                    'basalid' => $tongvv['id'],
                                    'markid' => $yuanvv['markid'],
                                    'type' => $yuanvv['type'],
                                    'basetype' => $yuanvv['basetype'],
                                    'name' => $yuanvv['name'],
                                    'guige' => $yuanvv['guige'],
                                    'valunit' => $yuanvv['valunit'],
                                    'content' => $yuanvv['content'],
                                    'content_exp' => $yuanvv['content_exp'],
                                    'loss_rate' => $yuanvv['loss_rate'],
                                    'no_price' => $yuanvv['no_price'],
                                    'price' => $yuanvv['price'],
                                    'explain' => $yuanvv['explain'],
                                ]);
                            }
                        }
                    }
                }

                foreach ($tonglist as $gengvv){
                    $gengBasalList = MainBasalListModel::where(['basalid'=>$gengvv['id']])->select()->toArray();

                    $updss['id'] = $gengvv['id'];
                    $updss['renprice'] = 0;
                    $updss['caiprice'] = 0;
                    $updss['jiprice'] = 0;
                    $updss['fenprice'] = 0;
                    foreach ($gengBasalList as $vvv){
                        if($vvv['type'] == 1) $updss['renprice'] += $vvv['price'];
                        if($vvv['type'] == 2) $updss['caiprice'] += $vvv['price'];
                        if($vvv['type'] == 3) $updss['jiprice'] += $vvv['price'];
                        if($vvv['type'] == 4) $updss['fenprice'] += $vvv['price'];
                    }
                    $updss['price'] = $updss['renprice'] + $updss['caiprice'] + $updss['jiprice'] + $updss['fenprice'];

                    $updss['renfee'] = round($updss['renprice'] * $gengvv['enword'],2);
                    $updss['caifee'] = round($updss['caiprice'] * $gengvv['enword'],2);
                    $updss['jifee'] = round($updss['jiprice'] * $gengvv['enword'],2);
                    $updss['fenfee'] = round($updss['fenprice'] * $gengvv['enword'],2);
                    $updss['money'] = $updss['renfee'] + $updss['caifee'] + $updss['jifee'] + $updss['fenfee'];
                    MainBasalModel::update($updss);


                    //处理工程量清单数据
                    $qing_data = MainQingListModel::where(['enginid'=>$gengvv['enginid'],'fenname'=>$gengvv['fenname'],
                        'enname'=>$gengvv['enname'], 'enfeat'=>$gengvv['enfeat'],'enunit'=>$gengvv['enunit']])->select()->toArray();
                    foreach ($qing_data as $item){
                        $item['enword'] = floatval($item['enword']);
                        $ins = [];
                        $ins['renprice'] = $updss['renprice'];
                        $ins['caiprice'] = $updss['caiprice'];
                        $ins['jiprice'] = $updss['jiprice'];
                        $ins['fenprice'] = $updss['fenprice'];
                        $ins['price'] = $updss['price'];
                        $ins['renfee_cur'] = round($updss['renprice'] * $item['enword'],2);
                        $ins['caifee_cur'] = round($updss['caiprice'] * $item['enword'],2);
                        $ins['jifee_cur'] = round($updss['jiprice'] * $item['enword'],2);
                        $ins['fenfee_cur'] = round($updss['fenprice'] * $item['enword'],2);
                        $ins['money'] = $ins['renfee_cur'] + $ins['caifee_cur'] + $ins['jifee_cur'] + $ins['fenfee_cur'];
                        MainQingListModel::where('id',$item['id'])->update($ins);
                    }
                }


                (new MainService())->update_at_main($basalinfo['enginid'], 'basal');
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id', 0, 'int');
            $data['data'] = MainBasalModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = MainBasalListModel::where(['basalid'=>$id])->select()->toArray();
            foreach ($list as &$item){
                $item['type_name'] = (new MainService())->get_main_type_name($item['type']);
            }
            $data['list'] = $list;

            $is_fenname = $request->get('is_fenname', 0, 'int');
            $is_encode = $request->get('is_encode', 0, 'int');
            $is_enname = $request->get('is_enname', 0, 'int');
            $is_enfeat = $request->get('is_enfeat', 0, 'int');
            $is_enunit = $request->get('is_enunit', 0, 'int');

            $tongWhere = [];
            if($is_fenname > 0) $tongWhere[] = ['fenname', '=', $data['data']['fenname']];
            if($is_encode > 0) $tongWhere[] = ['encode', '=', $data['data']['encode']];
            if($is_enname > 0) $tongWhere[] = ['enname', '=', $data['data']['enname']];
            if($is_enfeat > 0) $tongWhere[] = ['enfeat', '=', $data['data']['enfeat']];
            if($is_enunit > 0) $tongWhere[] = ['enunit', '=', $data['data']['enunit']];

            $tonglist = MainBasalModel::where($tongWhere)->where(['enginid'=>$data['data']['enginid']])
                ->where('id','neq',$data['data']['id'])->order('encode ASC')->select()->toArray();
            $data['tonglist'] = $tonglist;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    //基准费用
    public function list_mark(Request $request){
        $param = $request->post();
        $where[] = ['comid','=',$this->userinfo['comid']];
        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }

        $type = $request->post('type',1,'int');
        $where[] = ['type','=',$type];

        $data = [];
        $data['type'] = (new MainService())->get_main_type();
        if($type == 1){
            $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'mark1');
        }elseif($type == 2){
            $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'mark2');
        }elseif($type == 3){
            $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'mark3');
        }elseif($type == 4){
            $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'mark4');
        }
        $basetypearr = [];
        foreach ($data['type'] as $kk=>$vv){
            $basetypearr[$kk] = MainMarkTypeModel::where(['enginid'=>$param['enginid'],'type'=>$kk])->order('id ASC')
                ->field('id,name')->select()->toArray();
        }
        $data['basetypearr'] = $basetypearr;



        $sstypeArr = [];
        $list = [];
        $markList = MainMarkModel::where($where)->select()->toArray();
        foreach ($basetypearr[$param['type']] as $typevv){
            $sstypeArr[] = $typevv['name'];
            foreach ($markList as $k=>$v){
                if($v['basetype'] == $typevv['name']){
                    $list[] = $v;
                }
            }
        }
        foreach ($markList as $k=>$v){
            if(!in_array($v['basetype'], $sstypeArr)){
                $list[] = $v;
            }
        }



        foreach ($list as &$item){
            $item['usenum'] = MainbasallistModel::where(['enginid'=>$item['enginid'],'markid'=>$item['id']])->count();
        }
        $data['data'] = $list;

        $data['engininfo'] = MainEnginModel::where(['id'=>$param['enginid']])->find();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_mark(Request $request){
        if($this->request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try{
                $GengArr = [];
                MainMarkModel::where(['enginid'=>$param['enginid'],'type'=>$param['type']])->update(['isfake'=>1, 'isyuan'=>1]);
                foreach ($list as $vvv){
                    if($vvv['id'] > 0){
                        MainMarkModel::where(['id'=>$vvv['id']])->update([
                            'type' => $vvv['type'],
                            'basetype' => $vvv['basetype'],
                            'name' => $vvv['name'],
                            'guige' => $vvv['guige'],
                            'valunit' => $vvv['valunit'],
                            'content_exp' => $vvv['content_exp'],
                            'content' => $vvv['content'],
                            'loss_rate' => $vvv['loss_rate'],
                            'no_price' => $vvv['no_price'],
                            'price' => $vvv['price'],
                            'explain' => $vvv['explain'],
                            'source' => $vvv['source'],
                            'isfake' => 0,
                        ]);
                        MainBasalListModel::where(['enginid'=>$param['enginid'],'markid'=>$vvv['id']])->update([
                            'type' => $vvv['type'],
                            'basetype' => $vvv['basetype'],
                            'name' => $vvv['name'],
                            'guige' => $vvv['guige'],
                            'valunit' => $vvv['valunit'],
                            'content_exp' => $vvv['content_exp'],
                            'content' => $vvv['content'],
                            'loss_rate' => $vvv['loss_rate'],
                            'no_price' => $vvv['no_price'],
                            'price' => $vvv['price'],
                            'explain' => $vvv['explain'],
                        ]);
                        $curGeng = MainBasalListModel::where(['enginid'=>$param['enginid'],'markid'=>$vvv['id']])->column('basalid');
                        $GengArr = array_unique(array_merge($GengArr, $curGeng));
                    }else{

                        $vvv['comid'] = $this->userinfo['comid'];
                        $vvv['isyuan'] = 1;
                        unset($vvv['id']);

                        $markid = MainMarkModel::insertGetId($vvv);
                        MainBasalListModel::where(['enginid'=>$param['enginid'],'type'=>$vvv['type'], 'basetype'=>$vvv['basetype'],
                            'name'=>$vvv['name'],'guige'=>$vvv['guige'],'valunit'=>$vvv['valunit']])->update([
                            'content_exp' => $vvv['content_exp'],
                            'content' => $vvv['content'],
                            'loss_rate' => $vvv['loss_rate'],
                            'no_price' => $vvv['no_price'],
                            'price' => $vvv['price'],
                            'markid' => $markid,
                        ]);
                        $curGeng = MainBasalListModel::where(['enginid'=>$param['enginid'],'markid'=>$markid])->column('basalid');
                        $GengArr = array_unique(array_merge($GengArr, $curGeng));
                    }
                }

                $fakeArr = MainMarkModel::where(['enginid'=>$param['enginid'],'isfake'=>1])->select()->toArray();
                foreach ($fakeArr as $fakvv){
                    MainMarkModel::where(['id'=>$fakvv['id']])->delete();
                    $curGeng = MainBasalListModel::where(['enginid'=>$param['enginid'],'markid'=>$fakvv['id']])->column('basalid');
                    MainBasalListModel::where(['enginid'=>$param['enginid'],'markid'=>$fakvv['id']])->delete();
                    $GengArr = array_unique(array_merge($GengArr, $curGeng));
                }


                foreach ($GengArr as $gengId){
                    $gengBasal = MainBasalModel::where(['id'=>$gengId])->find();
                    $gengBasalList = MainBasalListModel::where(['basalid'=>$gengId])->select()->toArray();
                    $parentFenname[] = $gengBasal['fenname'];


                    $updss['id'] = $gengId;
                    $updss['renprice'] = 0;
                    $updss['caiprice'] = 0;
                    $updss['jiprice'] = 0;
                    $updss['fenprice'] = 0;
                    foreach ($gengBasalList as $vvv){
                        if($vvv['type'] == 1) $updss['renprice'] += $vvv['price'];
                        if($vvv['type'] == 2) $updss['caiprice'] += $vvv['price'];
                        if($vvv['type'] == 3) $updss['jiprice'] += $vvv['price'];
                        if($vvv['type'] == 4) $updss['fenprice'] += $vvv['price'];
                    }
                    $updss['price'] = $updss['renprice'] + $updss['caiprice'] + $updss['jiprice'] + $updss['fenprice'];

                    $updss['renfee'] = round($updss['renprice'] * $gengBasal['enword'],2);
                    $updss['caifee'] = round($updss['caiprice'] * $gengBasal['enword'],2);
                    $updss['jifee'] = round($updss['jiprice'] * $gengBasal['enword'],2);
                    $updss['fenfee'] = round($updss['fenprice'] * $gengBasal['enword'],2);
                    $updss['money'] = $updss['renfee'] + $updss['caifee'] + $updss['jifee'] + $updss['fenfee'];
                    MainBasalModel::update($updss);

                    //处理工程量清单数据
                    $qing_data = MainQingListModel::where(['enginid'=>$gengBasal['enginid'],'fenname'=>$gengBasal['fenname'],
                        'enname'=>$gengBasal['enname'], 'enfeat'=>$gengBasal['enfeat'],'enunit'=>$gengBasal['enunit']])->select()->toArray();
                    foreach ($qing_data as $item){
                        $item['enword'] = floatval($item['enword']);
                        $ins = [];
                        $ins['renprice'] = $updss['renprice'];
                        $ins['caiprice'] = $updss['caiprice'];
                        $ins['jiprice'] = $updss['jiprice'];
                        $ins['fenprice'] = $updss['fenprice'];
                        $ins['price'] = $updss['price'];
                        $ins['renfee_cur'] = round($updss['renprice'] * $item['enword'],2);
                        $ins['caifee_cur'] = round($updss['caiprice'] * $item['enword'],2);
                        $ins['jifee_cur'] = round($updss['jiprice'] * $item['enword'],2);
                        $ins['fenfee_cur'] = round($updss['fenprice'] * $item['enword'],2);
                        $ins['money'] = $ins['renfee_cur'] + $ins['caifee_cur'] + $ins['jifee_cur'] + $ins['fenfee_cur'];
                        MainQingListModel::where('id',$item['id'])->update($ins);
                    }
                }

                if($param['type'] == 1){
                    (new MainService())->update_at_main($param['enginid'], 'mark1');
                }elseif($param['type'] == 2){
                    (new MainService())->update_at_main($param['enginid'], 'mark2');
                }elseif($param['type'] == 3){
                    (new MainService())->update_at_main($param['enginid'], 'mark3');
                }elseif($param['type'] == 4){
                    (new MainService())->update_at_main($param['enginid'], 'mark4');
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function guan_mark(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try {
                MainMarkTypeModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$param['enginid'],'type'=>$param['type']])->delete();

                foreach ($list as $k=>$vv){
                    $vv['comid'] = $this->userinfo['comid'];
                    $vv['enginid'] = $param['enginid'];
                    $vv['type'] = $param['type'];
                    $vv['sort'] = $k;
                    MainMarkTypeModel::insert($vv);
                }

                if($param['type'] == 1){
                    (new MainService())->update_at_main($param['enginid'], 'mark1');
                }elseif($param['type'] == 2){
                    (new MainService())->update_at_main($param['enginid'], 'mark2');
                }elseif($param['type'] == 3){
                    (new MainService())->update_at_main($param['enginid'], 'mark3');
                }elseif($param['type'] == 4){
                    (new MainService())->update_at_main($param['enginid'], 'mark4');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->get('enginid', 0, 'int');
            $type = $request->get('type', 0, 'int');
            $chong = $request->get('chong', 0, 'int');
            if($chong > 0){
                $typaArr = [
                    1 => 'basetype_ren',
                    2 => 'basetype_cai',
                    3 => 'basetype_ji',
                    4 => 'basetype_fen'
                ];
                $renId = MainOptionModel::where(['comid'=>$this->userinfo['comid'],'num'=>$typaArr[$type]])->value('id');
                $data = MainOptionModel::field('name')->where(['comid'=>$this->userinfo['comid'],'pid'=>$renId])->order('sort ASC')->select()->toArray();
            }else{
                $data = MainMarkTypeModel::where(['enginid'=>$enginid, 'type'=>$type])->order('sort ASC')->select()->toArray();
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function yin_mark(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.id','neq',$param['enginid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }

        $type = $param['type'];

        $data['data'] = MainEnginModel::alias('e')
            ->field('e.id,e.name')
            ->where($where)
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key)use($type){
                $item['list'] = MainMarkModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'type'=>$type])->select()->toArray();
                $item['listnum'] = count($item['list']);
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function chong_mark(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['mark.deleted_user','=', 0];
        $where[] = ['mark.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['mark.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['mark.name','like', '%'.$param['name'].'%'];
        }

        if($param['type'] == 1){
            $data['data'] = MainMarkRenModel::alias('mark')
                ->field('mark.*')
                ->where($where)
                ->order('mark.id DESC')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    $list = MainMarkRenListModel::where(['markid'=>$item['id']])->select()->toArray();
                    foreach ($list as &$vvv){
                        $vvv['basetype'] = (new MainService())->get_base_showname('basetype_ren', $vvv['basetype']);
                    }
                    $item['list'] = $list;
                    $item['listnum'] = count($list);
                    $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                    return $item;
                })->toArray();
        }
        if($param['type'] == 2){
            $data['data'] = MainMarkCaiModel::alias('mark')
                ->field('mark.*')
                ->where($where)
                ->order('mark.id DESC')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    $list = MainMarkCaiListModel::where(['markid'=>$item['id']])->select()->toArray();
                    foreach ($list as &$vvv){
//                        $vvv['basetype'] = (new MainService())->get_base_showname('basetype_cai', $vvv['basetype']);
                    }
                    $item['list'] = $list;
                    $item['listnum'] = count($list);
                    $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                    return $item;
                })->toArray();
        }
        if($param['type'] == 3){
            $data['data'] = MainMarkJiModel::alias('mark')
                ->field('mark.*')
                ->where($where)
                ->order('mark.id DESC')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    $list = MainMarkJiListModel::where(['markid'=>$item['id']])->select()->toArray();
                    foreach ($list as &$vvv){
                        $vvv['basetype'] = (new MainService())->get_base_showname('basetype_ji', $vvv['basetype']);
                    }
                    $item['list'] = $list;
                    $item['listnum'] = count($list);
                    $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                    return $item;
                })->toArray();
        }
        if($param['type'] == 4){
            $data['data'] = MainMarkFenModel::alias('mark')
                ->field('mark.*')
                ->where($where)
                ->order('mark.id DESC')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    $list = MainMarkFenListModel::where(['markid'=>$item['id']])->select()->toArray();
                    foreach ($list as &$vvv){
                        $vvv['basetype'] = (new MainService())->get_base_showname('basetype_fen', $vvv['basetype']);
                    }
                    $item['list'] = $list;
                    $item['listnum'] = count($list);
                    $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                    return $item;
                })->toArray();
        }
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function check_main_base_cai(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cai.deleted_user','=', 0];
        $where[] = ['cai.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['cai.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['basetype']) && !empty($param['basetype'])){
            $where[] = ['cai.basetype_cai','=', $param['basetype']];
        }
        if(isset($param['basetype_cai']) && !empty($param['basetype_cai'])){
            $where[] = ['cai.basetype_cai','=', $param['basetype_cai']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['cai.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cai.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['xiangtype']) && !empty($param['xiangtype'])){
            $where[] = ['cai.xiangtype','=', $param['xiangtype']];
        }
        if(isset($param['shidt']) && !empty($param['shidt'])){
            $where[] = ['cai.shidt','like', '%'.$param['shidt'].'%'];
        }
        if(isset($param['gongtype_cai']) && !empty($param['gongtype_cai'])){
            $where[] = ['cai.gongtype_cai','=', $param['gongtype_cai']];
        }
        if(isset($param['painame']) && !empty($param['painame'])){
            $where[] = ['cai.painame','like', '%'.$param['painame'].'%'];
        }
        if(isset($param['pinname']) && !empty($param['pinname'])){
            $where[] = ['cai.pinname','like', '%'.$param['pinname'].'%'];
        }
        if(isset($param['guige']) && !empty($param['guige'])){
            $where[] = ['cai.guige','like', '%'.$param['guige'].'%'];
        }
        if(isset($param['valunit']) && !empty($param['valunit'])){
            $where[] = ['cai.valunit','like', '%'.$param['valunit'].'%'];
        }
        if(isset($param['noratefee']) && !empty($param['noratefee'])){
            $where[] = ['cai.noratefee','like', '%'.$param['noratefee'].'%'];
        }
        if(isset($param['gongname']) && !empty($param['gongname'])){
            $where[] = ['cai.gongname','like', '%'.$param['gongname'].'%'];
        }
        if(isset($param['gongtel']) && !empty($param['gongtel'])){
            $where[] = ['cai.gongtel','like', '%'.$param['gongtel'].'%'];
        }
        if(isset($param['pridt']) && !empty($param['pridt'])){
            $where[] = ['cai.pridt','between', explode(' - ', $param['pridt'])];
        }
        if(isset($param['explain']) && !empty($param['explain'])){
            $where[] = ['cai.explain','like', '%'.$param['explain'].'%'];
        }
        if(isset($param['explaintwo']) && !empty($param['explaintwo'])){
            $where[] = ['cai.explaintwo','like', '%'.$param['explaintwo'].'%'];
        }



        $data['basetype_cai'] = (new MainService())->get_base_info('basetype_cai');
        $data['is_basetype_cai'] = isset($param['basetype_cai']) ? $param['basetype_cai'] : '';

        $data['xiangtype'] = (new MainService())->get_base_info('xiangtype');
        $data['is_xiangtype'] = isset($param['xiangtype']) ? $param['xiangtype'] : '';

        $data['gongtype_cai'] = (new MainService())->get_base_info('gongtype_cai');
        $data['is_gongtype_cai'] = isset($param['gongtype_cai']) ? $param['gongtype_cai'] : '';


        $data['data'] = MainBaseCaiModel::alias('cai')
            ->field('cai.*')
            ->where($where)
            ->order('cai.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                $item['basetype_cai'] = (new MainService())->get_base_showname('basetype_cai', $item['basetype_cai']);
                $item['xiangtype'] = (new MainService())->get_base_showname('xiangtype', $item['xiangtype']);
                $item['gongtype_cai'] = (new MainService())->get_base_showname('gongtype_cai', $item['gongtype_cai']);
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function check_main_base_ren(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['ren.deleted_user','=', 0];
        $where[] = ['ren.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['ren.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['basetype']) && !empty($param['basetype'])){
            $where[] = ['cai.basetype_ren','=', $param['basetype']];
        }
        if(isset($param['basetype_ren']) && !empty($param['basetype_ren'])){
            $where[] = ['ren.basetype_ren','=', $param['basetype_ren']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['ren.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['ren.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['xiangtype']) && !empty($param['xiangtype'])){
            $where[] = ['ren.xiangtype','=', $param['xiangtype']];
        }
        if(isset($param['shidt']) && !empty($param['shidt'])){
            $where[] = ['ren.shidt','like', '%'.$param['shidt'].'%'];
        }
        if(isset($param['gongtype_ren']) && !empty($param['gongtype_ren'])){
            $where[] = ['ren.gongtype_ren','=', $param['gongtype_ren']];
        }
        if(isset($param['pinname']) && !empty($param['pinname'])){
            $where[] = ['ren.pinname','like', '%'.$param['pinname'].'%'];
        }
        if(isset($param['guige']) && !empty($param['guige'])){
            $where[] = ['ren.guige','like', '%'.$param['guige'].'%'];
        }
        if(isset($param['valunit']) && !empty($param['valunit'])){
            $where[] = ['ren.valunit','like', '%'.$param['valunit'].'%'];
        }
        if(isset($param['noratefee']) && !empty($param['noratefee'])){
            $where[] = ['ren.noratefee','like', '%'.$param['noratefee'].'%'];
        }
        if(isset($param['gongtel']) && !empty($param['gongtel'])){
            $where[] = ['ren.gongtel','like', '%'.$param['gongtel'].'%'];
        }
        if(isset($param['pridt']) && !empty($param['pridt'])){
            $where[] = ['ren.pridt','between', explode(' - ', $param['pridt'])];
        }
        if(isset($param['explain']) && !empty($param['explain'])){
            $where[] = ['ren.explain','like', '%'.$param['explain'].'%'];
        }
        if(isset($param['explaintwo']) && !empty($param['explaintwo'])){
            $where[] = ['ren.explaintwo','like', '%'.$param['explaintwo'].'%'];
        }



        $data['basetype_ren'] = (new MainService())->get_base_info('basetype_ren');
        $data['is_basetype_ren'] = isset($param['basetype_ren']) ? $param['basetype_ren'] : '';

        $data['xiangtype'] = (new MainService())->get_base_info('xiangtype');
        $data['is_xiangtype'] = isset($param['xiangtype']) ? $param['xiangtype'] : '';

        $data['gongtype_ren'] = (new MainService())->get_base_info('gongtype_ren');
        $data['is_gongtype_ren'] = isset($param['gongtype_ren']) ? $param['gongtype_ren'] : '';


        $data['data'] = MainBaseRenModel::alias('ren')
            ->field('ren.*')
            ->where($where)
            ->order('ren.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                $item['basetype_ren'] = (new MainService())->get_base_showname('basetype_ren', $item['basetype_ren']);
                $item['xiangtype'] = (new MainService())->get_base_showname('xiangtype', $item['xiangtype']);
                $item['gongtype_ren'] = (new MainService())->get_base_showname('gongtype_ren', $item['gongtype_ren']);
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function check_main_base_ji(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['ji.deleted_user','=', 0];
        $where[] = ['ji.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['ji.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['basetype']) && !empty($param['basetype'])){
            $where[] = ['cai.basetype_ji','=', $param['basetype']];
        }
        if(isset($param['basetype_ji']) && !empty($param['basetype_ji'])){
            $where[] = ['ji.basetype_ji','=', $param['basetype_ji']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['ji.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['ji.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['xiangtype']) && !empty($param['xiangtype'])){
            $where[] = ['ji.xiangtype','=', $param['xiangtype']];
        }
        if(isset($param['shidt']) && !empty($param['shidt'])){
            $where[] = ['ji.shidt','like', '%'.$param['shidt'].'%'];
        }
        if(isset($param['gongtype_ji']) && !empty($param['gongtype_ji'])){
            $where[] = ['ji.gongtype_ji','=', $param['gongtype_ji']];
        }
        if(isset($param['pinname']) && !empty($param['pinname'])){
            $where[] = ['ji.pinname','like', '%'.$param['pinname'].'%'];
        }
        if(isset($param['guige']) && !empty($param['guige'])){
            $where[] = ['ji.guige','like', '%'.$param['guige'].'%'];
        }
        if(isset($param['valunit']) && !empty($param['valunit'])){
            $where[] = ['ji.valunit','like', '%'.$param['valunit'].'%'];
        }
        if(isset($param['noratefee']) && !empty($param['noratefee'])){
            $where[] = ['ji.noratefee','like', '%'.$param['noratefee'].'%'];
        }
        if(isset($param['gongtel']) && !empty($param['gongtel'])){
            $where[] = ['ji.gongtel','like', '%'.$param['gongtel'].'%'];
        }
        if(isset($param['pridt']) && !empty($param['pridt'])){
            $where[] = ['ji.pridt','between', explode(' - ', $param['pridt'])];
        }
        if(isset($param['explain']) && !empty($param['explain'])){
            $where[] = ['ji.explain','like', '%'.$param['explain'].'%'];
        }
        if(isset($param['explaintwo']) && !empty($param['explaintwo'])){
            $where[] = ['ji.explaintwo','like', '%'.$param['explaintwo'].'%'];
        }



        $data['basetype_ji'] = (new MainService())->get_base_info('basetype_ji');
        $data['is_basetype_ji'] = isset($param['basetype_ji']) ? $param['basetype_ji'] : '';

        $data['xiangtype'] = (new MainService())->get_base_info('xiangtype');
        $data['is_xiangtype'] = isset($param['xiangtype']) ? $param['xiangtype'] : '';

        $data['gongtype_ji'] = (new MainService())->get_base_info('gongtype_ji');
        $data['is_gongtype_ji'] = isset($param['gongtype_ji']) ? $param['gongtype_ji'] : '';


        $data['data'] = MainBaseJiModel::alias('ji')
            ->field('ji.*')
            ->where($where)
            ->order('ji.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                $item['basetype_ji'] = (new MainService())->get_base_showname('basetype_ji', $item['basetype_ji']);
                $item['xiangtype'] = (new MainService())->get_base_showname('xiangtype', $item['xiangtype']);
                $item['gongtype_ji'] = (new MainService())->get_base_showname('gongtype_ji', $item['gongtype_ji']);
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function check_main_base_fen(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['fen.deleted_user','=', 0];
        $where[] = ['fen.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['fen.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['basetype']) && !empty($param['basetype'])){
            $where[] = ['cai.basetype_fen','=', $param['basetype']];
        }
        if(isset($param['basetype_fen']) && !empty($param['basetype_fen'])){
            $where[] = ['fen.basetype_fen','=', $param['basetype_fen']];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['fen.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['fen.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['xiangtype']) && !empty($param['xiangtype'])){
            $where[] = ['fen.xiangtype','=', $param['xiangtype']];
        }
        if(isset($param['shidt']) && !empty($param['shidt'])){
            $where[] = ['fen.shidt','like', '%'.$param['shidt'].'%'];
        }
        if(isset($param['gongtype_fen']) && !empty($param['gongtype_fen'])){
            $where[] = ['fen.gongtype_fen','=', $param['gongtype_fen']];
        }
        if(isset($param['pinname']) && !empty($param['pinname'])){
            $where[] = ['fen.pinname','like', '%'.$param['pinname'].'%'];
        }
        if(isset($param['guige']) && !empty($param['guige'])){
            $where[] = ['fen.guige','like', '%'.$param['guige'].'%'];
        }
        if(isset($param['valunit']) && !empty($param['valunit'])){
            $where[] = ['fen.valunit','like', '%'.$param['valunit'].'%'];
        }
        if(isset($param['noratefee']) && !empty($param['noratefee'])){
            $where[] = ['fen.noratefee','like', '%'.$param['noratefee'].'%'];
        }
        if(isset($param['gongtel']) && !empty($param['gongtel'])){
            $where[] = ['fen.gongtel','like', '%'.$param['gongtel'].'%'];
        }
        if(isset($param['pridt']) && !empty($param['pridt'])){
            $where[] = ['fen.pridt','between', explode(' - ', $param['pridt'])];
        }
        if(isset($param['explain']) && !empty($param['explain'])){
            $where[] = ['fen.explain','like', '%'.$param['explain'].'%'];
        }
        if(isset($param['explaintwo']) && !empty($param['explaintwo'])){
            $where[] = ['fen.explaintwo','like', '%'.$param['explaintwo'].'%'];
        }



        $data['basetype_fen'] = (new MainService())->get_base_info('basetype_fen');
        $data['is_basetype_fen'] = isset($param['basetype_fen']) ? $param['basetype_fen'] : '';

        $data['xiangtype'] = (new MainService())->get_base_info('xiangtype');
        $data['is_xiangtype'] = isset($param['xiangtype']) ? $param['xiangtype'] : '';

        $data['gongtype_fen'] = (new MainService())->get_base_info('gongtype_fen');
        $data['is_gongtype_fen'] = isset($param['gongtype_fen']) ? $param['gongtype_fen'] : '';


        $data['data'] = MainBaseFenModel::alias('fen')
            ->field('fen.*')
            ->where($where)
            ->order('fen.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                $item['basetype_fen'] = (new MainService())->get_base_showname('basetype_fen', $item['basetype_fen']);
                $item['xiangtype'] = (new MainService())->get_base_showname('xiangtype', $item['xiangtype']);
                $item['gongtype_fen'] = (new MainService())->get_base_showname('gongtype_fen', $item['gongtype_fen']);
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function basal_mark(Request $request){
        $param = $request->post();
        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }
        if(isset($param['markid']) && !empty($param['markid'])){
            $where[] = ['markid','=',$param['markid']];
        }

        if(isset($param['basalid']) && !empty($param['basalid'])){
            $listinfo = MainBasalListModel::where(['enginid'=>$param['enginid'],'basalid'=>$param['basalid']])->select()->toArray();
            foreach ($listinfo as &$item){
                $item['type_name'] = (new MainService())->get_main_type_name($item['type']);
            }
            $data['basallist'] = $listinfo;
        }else{
            $basalidArr = MainBasalListModel::where($where)->group('basalid')->column('basalid');
            $basalinfo = MainBasalModel::where('id','in',$basalidArr)->select()->toArray();
            $data['basal'] = $basalinfo;
        }

        return outputJson(2000,lang('code_2000'),$data);
    }
    //含量指标分析表
    public function add_analy(Request $request)
    {
        if($this->request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);

            Db::startTrans();
            try{
                foreach ($list as $item){
                    $item['updated_user'] = $this->userinfo['id'];
                    $item['updated_at'] = date('Y-m-d H:i:s');
                    MainQingModel::update($item);
                }

                (new MainService())->update_at_main($param['enginid'], 'analy');
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->get('enginid', 0, 'int');
            $data['data'] = MainQingModel::where('enginid',$enginid)->order('sort ASC,id ASC')->select()->toArray();
            foreach ($data['data'] as &$item){
                $item['steel_list'] = json_decode($item['steel_list'], true) ?: [];
                $item['concrete_list'] = json_decode($item['concrete_list'], true) ?: [];
                $item['template_list'] = json_decode($item['template_list'], true) ?: [];
                $item['masonry_list'] = json_decode($item['masonry_list'], true) ?: [];
                $item['ceiling_list'] = json_decode($item['ceiling_list'], true) ?: [];
                $item['outside_list'] = json_decode($item['outside_list'], true) ?: [];
                $item['ground_list'] = json_decode($item['ground_list'], true) ?: [];
                $item['inside_list'] = json_decode($item['inside_list'], true) ?: [];
                $item['doors_list'] = json_decode($item['doors_list'], true) ?: [];
                $item['jsj_list'] = json_decode($item['jsj_list'], true) ?: [];
            }

            $data['tit'] = (new MainService())->get_maineditshi($enginid,'analy');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    //工料机汇总
    public function list_gongji(Request $request)
    {
        $param = $request->post();
        get_page($param);

        $where = [];
        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['enginid','=',$param['enginid']];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['type','=',$param['type']];
        }

        $data = MainBasalListModel::where($where)->field('*')
            ->group(['type','basetype','name','guige','valunit'])
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item, $key){
                $list_data = MainBasalListModel::alias('list')->field('list.price,b.enword')
                    ->leftJoin('main_basal b','b.id = list.basalid')
                    ->where(['list.type'=>$item['type'],'list.basetype'=>$item['basetype'],'list.name'=>$item['name'],
                        'list.guige'=>$item['guige'],'list.valunit'=>$item['valunit']])->select();
                $item['number'] = $item['money'] = 0;
                foreach ($list_data as $v){
                    $item['number'] += $v['enword'];
                    $item['money'] += $v['enword'] * $v['price'];
                }
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }

    //模板支撑
    public function list_week_lease(Request $request)
    {
        $param = $request->post();
        $engininfo = MainEnginModel::where(['id'=>$param['enginid']])->find();
        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'week_lease');

        $list = MainQingModel::where('enginid',$param['enginid'])->field('qingname,id,area')
            ->order(['sort'=>'asc','id'=>'asc'])->select()->toArray();
        foreach ($list as &$item){
            $item['children'] = MainWeekLeaseModel::where(['qingid'=>$item['id'],'enginid'=>$param['enginid']])->select()->toArray();
        }

        $data['list'] = $list;
        $data['week_lease'] = $engininfo['week_lease'];
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_week_lease(Request $request)
    {
        if($request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try{
                MainEnginModel::where('id',$param['enginid'])->update(['week_lease'=>$param['week_lease']]);
                MainWeekLeaseModel::where('enginid',$param['enginid'])->delete();
                foreach ($list as $item){
                    $item['updated_user'] = $this->userinfo['id'];
                    $item['updated_at'] = date('Y-m-d H:i:s');
                    MainWeekLeaseModel::insert($item);
                }

                (new MainService())->update_at_main($param['enginid'], 'week_lease');
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
    }

    //周转材
    public function list_week_stuff(Request $request)
    {
        $param = $request->post();
        $engininfo = MainEnginModel::where(['id'=>$param['enginid']])->find();
        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'week_stuff');

        $list = MainQingModel::where('enginid',$param['enginid'])->field('qingname,id,area')
            ->order(['sort'=>'asc','id'=>'asc'])->select()->toArray();
        foreach ($list as &$item){
            $stuff_data = MainWeekStuffModel::where(['qingid'=>$item['id'],'enginid'=>$param['enginid']])->select()->toArray();
            $zhi = MainWeekLeaseModel::where(['qingid'=>$item['id'],'enginid'=>$param['enginid']])->field('sum(money) as money')->find();
            if(!$stuff_data){
                $item['children'] = [
                    ['qingid'=>$item['id'],'name'=>'木模板材料费','unit'=>'M2','area'=>$item['area'],'template'=>0,'content'=>0,'mold'=>0,'ceng'=>'0','num'=>0,'chan'=>'0','no_price'=>0,'money'=>0,'pin_money'=>0,'explain'=>''],
                    ['qingid'=>$item['id'],'name'=>'木方材料费','unit'=>'根','area'=>$item['area'],'template'=>0,'content'=>0,'mold'=>0,'num'=>15,'no_price'=>0,'money'=>0,'pin_money'=>0,'explain'=>''],
                    ['qingid'=>$item['id'],'name'=>'支撑体系','unit'=>'M2','area'=>$item['area'],'template'=>0,'content'=>0,'mold'=>0,'num'=>0,'no_price'=>0,'money'=>$zhi['money'],'pin_money'=>0,'explain'=>''],
                    ['qingid'=>$item['id'],'name'=>'辅材','unit'=>'','area'=>$item['area'],'template'=>0,'content'=>0,'mold'=>0,'num'=>0,'no_price'=>0,'money'=>0,'pin_money'=>0,'explain'=>''],
                    ['name'=>'合计','money'=>'0','pin_money'=>'0']
                ];
            }else{
                $money = $pin_money = 0; $template = 0;
                $zhi_moeny = 0; $zhi_pin_money = 0; // 支撑体系 合价，平方价格
                $temp_list = [];
                foreach ($stuff_data as $v){
                    if($v['name'] == '木模板材料费'){
                        $template = $v['template'];
                    }

                    if($v['name'] == '轮扣' || $v['name'] == '套扣' || $v['name'] == '盘扣'){
                        $zhi_moeny += $v['money'];
                        $money += $v['money'];
                        unset($v);
                    }else{
                        $money += $v['money'];
                        $pin_money += $v['pin_money'];
                        $temp_list[] = $v;
                    }
                }

                $zhi_moeny += $zhi['money'];
                if(!empty($template)){
                    $zhi_pin_money = $zhi_moeny / $template;
                }


                $zhi_explain = '';
                foreach ($stuff_data as $sss){
                    if($sss['qingid'] == $item['id'] && $sss['name'] == '支撑体系'){
                        $zhi_explain = $sss['explain'];
                    }
                }
                $arr = ['qingid'=>$item['id'],'name'=>'支撑体系','unit'=>'M2','area'=>$item['area'],'template'=>0,'content'=>0,'mold'=>0,'num'=>0,
                    'no_price'=>0,'money'=>$zhi_moeny,'pin_money'=>round($zhi_pin_money,2),'explain'=>$zhi_explain];
                $temp_list[2] = $arr;

                unset($v);
                array_push($temp_list, ['name'=>'合计','money'=>$money,'pin_money'=>$pin_money]);
                $item['children'] = $temp_list;
            }
        }


        $data['list'] = $list;
        $data['week_stuff'] = $engininfo['week_stuff'];
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_week_stuff(Request $request)
    {
        if($request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);
            Db::startTrans();
            try{
                MainEnginModel::where('id',$param['enginid'])->update(['week_stuff'=>$param['week_stuff']]);
                MainWeekStuffModel::where('enginid',$param['enginid'])->delete();
                foreach ($list as $item){
                    $item['updated_user'] = $this->userinfo['id'];
                    $item['updated_at'] = date('Y-m-d H:i:s');
                    MainWeekStuffModel::insert($item);
                }

                (new MainService())->update_at_main($param['enginid'], 'week_stuff');
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
    }

    //间接费
    public function list_jian_engin(Request $request){
        $param = $request->post();
        $type = $request->post('type', 'chui', 'string');

        if($type == 'chui'){
            $list = (new MainService())->get_main_jian_engin_chui($param['enginid']);
        }elseif($type == 'cuo'){
            $list = (new MainService())->get_main_jian_engin_cuo($param['enginid']);
        }elseif($type == 'gong'){
            $list = (new MainService())->get_main_jian_engin_gong($param['enginid']);
        }elseif($type == 'guan'){
            $list = (new MainService())->get_main_jian_engin_guan($param['enginid']);
        }elseif($type == 'yuone'){
            $list = (new MainService())->get_main_jian_engin_yuone($param['enginid']);
        }elseif($type == 'yutwo'){
            $list = (new MainService())->get_main_jian_engin_yutwo($param['enginid']);
        }

        $data['list'] = $list;
        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],$type);
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_jian_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try {

                if($param['type'] == 'chui'){
                    MainJianEnginChuiModel::where(['enginid'=>$param['enginid']])->delete();
                    (new MainService())->add_main_jian_engin_chui($list, $param['enginid']);
                }
                if($param['type'] == 'cuo'){
                    MainJianEnginCuoModel::where(['enginid'=>$param['enginid']])->delete();
                    (new MainService())->add_main_jian_engin_cuo($list, $param['enginid']);
                }
                if($param['type'] == 'gong'){
                    MainJianEnginGongModel::where(['enginid'=>$param['enginid']])->delete();
                    (new MainService())->add_main_jian_engin_gong($list, $param['enginid']);
                }
                if($param['type'] == 'guan'){
                    MainJianEnginGuanModel::where(['enginid'=>$param['enginid']])->delete();
                    (new MainService())->add_main_jian_engin_guan($list, $param['enginid']);
                }
                if($param['type'] == 'yuone'){
                    MainJianEnginGuanModel::where(['enginid'=>$param['enginid']])->delete();
                    (new MainService())->add_main_jian_engin_yuone($list, $param['enginid']);
                }
                if($param['type'] == 'yutwo'){
                    MainJianEnginGuanModel::where(['enginid'=>$param['enginid']])->delete();
                    (new MainService())->add_main_jian_engin_yutwo($list, $param['enginid']);
                }

                (new MainService())->update_at_main($param['enginid'], $param['type']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            $data['editshi'] = (new MainService())->get_editshi();
            return outputJson(2000,lang('code_2000'),$data);
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = MainJianChuiModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = (new MainService())->get_main_jian_chui_list($data['data']['id']);
            $data['list'] = $list;
            $data['editshi'] = (new MainService())->get_editshi($data['data']['updated_at'],$data['data']['updated_user']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    //单方造价分析表
    public function list_zaofen(Request $request)
    {
        $param = $request->post();
        $where[] = ['enginid','=',$param['enginid']];

        $engininfo = MainEnginModel::where(['id'=>$param['enginid']])->find();
        $data = MainBasalModel::field('fenname')->where($where)->group('fenname')->order('id ASC')->select()->toArray();
        foreach ($data as &$item){
            $item['fee_cai'] = 0;
            $item['fee_ren'] = 0;
            $item['fee_zhuan'] = 0;
            $item['fee_ji'] = 0;
            $info = MainBasalModel::where($where)->where(['fenname'=>$item['fenname']])->order('id ASC')->select()->toArray();
            foreach ($info as $vvv){
                $item['fee_cai'] += $vvv['caifee'];
                $item['fee_ren'] += $vvv['renfee'];
                $item['fee_zhuan'] += $vvv['fenfee'];
                $item['fee_ji'] += $vvv['jifee'];
            }
            $item['fee_zong'] = $item['fee_cai'] + $item['fee_ren'] + $item['fee_zhuan'] + $item['fee_ji'];

            $item['fang_cai'] = 0;
            $item['fang_ren'] = 0;
            $item['fang_zhuan'] = 0;
            $item['fang_ji'] = 0;
            if($engininfo['mian'] > 0){
                $item['fang_cai'] = round($item['fee_cai'] / $engininfo['mian'], 2);
                $item['fang_ren'] = round($item['fee_ren'] / $engininfo['mian'], 2);
                $item['fang_zhuan'] = round($item['fee_zhuan'] / $engininfo['mian'], 2);
                $item['fang_ji'] = round($item['fee_ji'] / $engininfo['mian'], 2);
            }

            $item['fee_zong'] = round($item['fee_zong'], 2);
            $item['fee_ren'] = round($item['fee_ren'], 2);
            $item['fee_cai'] = round($item['fee_cai'], 2);
            $item['fee_ji'] = round($item['fee_ji'], 2);
            $item['fee_zhuan'] = round($item['fee_zhuan'], 2);
            $item['fang_ren'] = round($item['fang_ren'], 2);
            $item['fang_cai'] = round($item['fang_cai'], 2);
            $item['fang_ji'] = round($item['fang_ji'], 2);
            $item['fang_zhuan'] = round($item['fang_zhuan'], 2);

        }
        return outputJson(2000,lang('code_2000'),$data);
    }

    //资金成本表
    public function list_huizi(Request $request)
    {
        $param = $request->post();
        get_page($param);

        $engininfo = MainEnginModel::where(['id'=>$param['enginid']])->find();
        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'huizi');

        $qingData = MainQingModel::where('enginid',$param['enginid'])->select()->toArray();

        $jianArr = (new MainService())->get_jianArr($param['enginid']);
        $qingArr = (new MainService())->get_huizi_qingArr($param['enginid']);
        $list = MainHuiziModel::where(['enginid'=>$param['enginid']])->select()->toArray();


        $chanAllList = []; // 存储第一个到最后一个的收款
        $zhiMoneyList = [];

        $shouMoneyList = [];
        $qiMoneyList = [];
        foreach ($list as $key=>&$item){
            // 当月产值
            $item['chanfee'] = (new MainService())->get_huizi_chan($item['enginid'], $item['chan'], $qingArr,$jianArr);
            // 获取当月产值的分类的数组 key => value 模式
            $chan_list = (new MainService())->get_chan_list($item['enginid'], $item['chan'], $qingArr,$jianArr);


            if($key == 0){
                $item['shoufee'] = 0;
                $shouMoneyList[] = $item['shoufee'];
            }else{
                // 当月收入，这个月的收入-前面月份的收入，并存入数组中
                $shoufee = (new MainService())->get_shou_money($item['enginid'], $item['shou'], $chanAllList, $key);

                $item['shoufee'] = 0;
                if($shoufee[0] > 0){
                    $item['shoufee'] = $shoufee[0] + array_sum($qiMoneyList) - array_sum($shouMoneyList);
                }
                $qiMoneyList[] = $shoufee[1];
                $shouMoneyList[] = $item['shoufee'];
            }


            if($key == 0){
                $item['zhifee'] = 0;
                $zhiMoneyList[] = $item['zhifee'];
            }else{
                $item['zhifee'] = (new MainService())->get_zhi_money($item['enginid'], $item['zhi'], $chanAllList, $key);
                if($item['zhifee'] > 0){
                    $item['zhifee'] = $item['zhifee'] - array_sum($zhiMoneyList);
                }
                $zhiMoneyList[] = $item['zhifee'];
            }


            if($key == 0){
                $item['leichan'] = $item['chanfee'];
            }else{
                $item['leichan'] = $item['chanfee'] + $list[$key-1]['leichan'];
            }

            if($key == 0){
                $item['leishou'] = $item['shoufee'];
            }else{
                $item['leishou'] = $item['shoufee'] + $list[$key-1]['leishou'];
            }


            if($key == 0){
                $item['leizhi'] = $item['zhifee'];
            }else{
                $item['leizhi'] = $item['zhifee'] + $list[$key-1]['leizhi'];
            }
            $item['dianzhi'] = $item['leizhi'] - $item['leishou'];
            $item['dianli'] = -($item['dianzhi'] * $item['dianrate']/100);


            $chanData = json_decode($item['chan'],true);
            $chanList = [];
            if($chanData){
                foreach ($chanData as $v){
                    if($v['key'] == 'qing'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }

                        $qingname = MainQingModel::where('id',$v['resvalue'])->value('qingname');
                        if (count($v['fenname']) > 0){
                            foreach ($v['fenname'] as $vv){
                                $money = MainQingListModel::where(['enginid'=>$item['enginid'],'qingid'=>$v['resvalue'],'fenname'=>$vv['fenname']])->sum('money');
                                // 分部清单总金额*完成比例*税后价系数*总完成比例
                                $vv['rate'] = empty($vv['rate']) ? 1 : $vv['rate'];
                                if(substr($vv['rate'], 0 , 1) === '='){
                                    $vv['rate'] = maths(substr($vv['rate'],  1));
                                }
                                $optmoney = $money * $vv['rate'] * $v['ratio'] * $v['rate'];
                                $arr = [
                                    'qingname' => $qingname,
                                    'rate' => $v['rate'],
                                    'ratio' => $v['ratio'],
                                    'fenname' => $vv['fenname'],
                                    'fenrate' => $vv['rate'],
                                    'money' => $money,
                                    'optmoney' => $optmoney
                                ];
                                $chanList[] = $arr;
                            }
                        }else{
                            $arr = [
                                'qingname' => $qingname,
                                'rate' => $v['rate'],
                                'ratio' => $v['ratio'],
                                'fenname' => '',
                                'fenrate' => '',
                                'money' => '',
                                'optmoney' => ''
                            ];
                            $chanList[] = $arr;
                        }
                    }else if($v['key'] == 'jian'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }

                        if($v['resvalue'] == 'chui'){
                            $qingname = '垂直运输费';
                        }else if($v['resvalue'] == 'cuo'){
                            $qingname = '措施费';
                        }else if($v['resvalue'] == 'gong'){
                            $qingname = '管理人员工资';
                        }else if($v['resvalue'] == 'guan'){
                            $qingname = '管理费';
                        }else if($v['resvalue'] == 'yuzhi'){
                            $qingname = '预置表1';
                        }else if($v['resvalue'] == 'yuzhitwo'){
                            $qingname = '预置表2';
                        }else{
                            $qingname = '';
                        }
                        $money = isset($jianArr[$v['resvalue']]) ? $jianArr[$v['resvalue']] : 0;
                        $optmoney = $money * $v['rate'] * $v['ratio'];
                        $arr = [
                            'qingname' => $qingname,
                            'rate' => $v['rate'],
                            'ratio' => $v['ratio'],
                            'fenname' => '',
                            'fenrate' => '',
                            'money' => $money,
                            'optmoney' => $optmoney
                        ];
                        $chanList[] = $arr;
                    }else if($v['key'] == 'tou'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }

                        $money = $engininfo['money'];
                        $optmoney = $money * $v['rate'] * $v['ratio'];
                        $arr = [
                            'qingname' => '投标价金额',
                            'rate' => $v['rate'],
                            'ratio' => $v['ratio'],
                            'fenname' => '',
                            'fenrate' => '',
                            'money' => $money,
                            'optmoney' => $optmoney
                        ];
                        $chanList[] = $arr;
                    }else if($v['key'] == 'qi'){
                        $v['rate'] = empty($v['rate']) ? 0 : $v['rate'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }


                        $money = 0;
                        if(substr($v['rate'], 0 , 1) === '='){
                            $money += maths(substr($v['rate'],  1));
                        }else{
                            $money += $v['rate'];
                        }
                        if($v['resvalue'] == '1'){
                            $qingname = '其他费用项1';
                        }else if($v['resvalue'] == '2'){
                            $qingname = '其他费用项2';
                        }
                        $arr = [
                            'qingname' => $qingname,
                            'rate' => $v['rate'],
                            'ratio' => $v['ratio'],
                            'fenname' => '',
                            'fenrate' => '',
                            'money' => $money,
                            'optmoney' => $money
                        ];
                        $chanList[] = $arr;
                    }
                }
            }
            $item['chan_list'] = $chanList;

            $shouData = json_decode($item['shou'],true);
            $shouList = [];
            if($shouData){
                foreach ($shouData as $v){
                    if($v['key'] == 'qing'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }

                        $qingname = MainQingModel::where('id',$v['resvalue'])->value('qingname');
                        // 获取列数据
                        $arr = array_column($chanAllList, (int)$v['resvalue']);
                        $money = array_sum($arr);
                        if(empty($money)) $money = 0;
                        if (count($shouMoneyList) == 1){
                            $tempArr = $shouMoneyList;
                        }else{
                            $tempArr = array_chunk($shouMoneyList,count($shouMoneyList) - 1);
                            $tempArr = $tempArr[0];
                        }
                        $optmoney = $money * $v['rate'] * $v['ratio'];
                        $arr = [
                            'qingname' => $qingname,
                            'rate' => $v['rate'],
                            'ratio' => $v['ratio'],
                            'fenname' => '',
                            'fenrate' => '',
                            'money' => '',
                            'optmoney' => $optmoney
                        ];
                        $shouList[] = $arr;
                    }else if($v['key'] == 'jian'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }

                        if($v['resvalue'] == 'chui'){
                            $qingname = '垂直运输费';
                        }else if($v['resvalue'] == 'cuo'){
                            $qingname = '措施费';
                        }else if($v['resvalue'] == 'gong'){
                            $qingname = '管理人员工资';
                        }else if($v['resvalue'] == 'guan'){
                            $qingname = '管理费';
                        }else if($v['resvalue'] == 'yuzhi'){
                            $qingname = '预置表1';
                        }else if($v['resvalue'] == 'yuzhitwo'){
                            $qingname = '预置表2';
                        }else{
                            $qingname = '';
                        }
                        $money = isset($jianArr[$v['resvalue']]) ? $jianArr[$v['resvalue']] : 0;
                        $optmoney = $money * $v['rate'] * $v['ratio'];
                        $arr = [
                            'qingname' => $qingname,
                            'rate' => $v['rate'],
                            'ratio' => $v['ratio'],
                            'fenname' => '',
                            'fenrate' => '',
                            'money' => $money,
                            'optmoney' => $optmoney
                        ];
                        $shouList[] = $arr;
                    }else if($v['key'] == 'tou'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }

                        $money = $engininfo['money'];
                        $optmoney = $money * $v['rate'] * $v['ratio'];
                        $arr = [
                            'qingname' => '投标价金额',
                            'rate' => $v['rate'],
                            'ratio' => $v['ratio'],
                            'fenname' => '',
                            'fenrate' => '',
                            'money' => $money,
                            'optmoney' => $optmoney
                        ];
                        $shouList[] = $arr;
                    }else if($v['key'] == 'qi'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }

                        $money = 0;
                        if(substr($v['rate'], 0 , 1) === '='){
                            $money += maths(substr($v['rate'],  1));
                        }else{
                            $money += $v['rate'];
                        }
                        if($v['resvalue'] == '1'){
                            $qingname = '其他费用项1';
                        }else if($v['resvalue'] == '2'){
                            $qingname = '其他费用项2';
                        }
                        $arr = [
                            'qingname' => $qingname,
                            'rate' => $v['rate'],
                            'ratio' => $v['ratio'],
                            'fenname' => '',
                            'fenrate' => '',
                            'money' => $money,
                            'optmoney' => $money
                        ];
                        $shouList[] = $arr;
                    }
                }
            }
            $item['shou_list'] = $shouList;


            $zhiData = json_decode($item['zhi'],true);
            $zhiList = [];
            if($zhiData){
                foreach ($zhiData as $v){
                    if(!isset($v['fenname']) || !is_array($v['fenname'])){
                        $v['fenname'] = [];
                    }
                    if($v['key'] == 'qing'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }

                        $qingname = MainQingModel::where('id',$v['resvalue'])->value('qingname');
                        if (count($v['fenname']) > 0){
                            if(isset($v['fenname']) && !is_array($v['fenname'])){
                                $v['fenname'] = json_decode($v['fenname'], true);
                            }
                            if($v['fenname']){
                                foreach ($v['fenname'] as $vv){
                                    $vv['rate_ren'] = empty($vv['rate_ren']) ? 0 : $vv['rate_ren'];
                                    $vv['rate_cai'] = empty($vv['rate_cai']) ? 0 : $vv['rate_cai'];
                                    $vv['rate_ji'] = empty($vv['rate_ji']) ? 0 : $vv['rate_ji'];
                                    $vv['rate_fen'] = empty($vv['rate_fen']) ? 0 : $vv['rate_fen'];

                                    if(substr($vv['rate_ren'], 0 , 1) === '='){
                                        $vv['rate_ren'] = maths(substr($vv['rate_ren'],  1));
                                    }
                                    if(substr($vv['rate_cai'], 0 , 1) === '='){
                                        $vv['rate_cai'] = maths(substr($vv['rate_cai'],  1));
                                    }
                                    if(substr($vv['rate_ji'], 0 , 1) === '='){
                                        $vv['rate_ji'] = maths(substr($vv['rate_ji'],  1));
                                    }
                                    if(substr($vv['rate_fen'], 0 , 1) === '='){
                                        $vv['rate_fen'] = maths(substr($vv['rate_fen'],  1));
                                    }

                                    $arrs = (new MainService())->get_huizi_zhiqingArr($item['enginid'],$vv['fenname']);
                                    $ren = $cai = $ji = $fen = 0;
                                    if(isset($arrs[$v['resvalue']][$vv['fenname']])){
                                        $ren = $arrs[$v['resvalue']][$vv['fenname']]['renfee'] * $vv['rate_ren'];
                                        $cai = $arrs[$v['resvalue']][$vv['fenname']]['caifee'] * $vv['rate_cai'];
                                        $ji = $arrs[$v['resvalue']][$vv['fenname']]['jifee'] * $vv['rate_ji'];
                                        $fen = $arrs[$v['resvalue']][$vv['fenname']]['fenfee'] * $vv['rate_fen'];
                                    }
                                    $optmoney = ($ren+$cai+$ji+$fen) * $v['rate'];
                                    if($ren != 0){
                                        $ren = $ren.'('.$vv['rate_ren_val'].')';
                                    }else{
                                        $ren = '';
                                    }
                                    if($cai != 0){
                                        $cai = $cai.'('.$vv['rate_cai_val'].')';
                                    }else{
                                        $cai = '';
                                    }
                                    if($ji != 0){
                                        $ji = $ji.'('.$vv['rate_ji_val'].')';
                                    }else{
                                        $ji = '';
                                    }
                                    if($fen != 0){
                                        $fen = $fen.'('.$vv['rate_fen_val'].')';
                                    }else{
                                        $fen = '';
                                    }
                                    $arr = [
                                        'qingname' => $qingname,
                                        'rate' => $v['rate'],
                                        'ratio' => '',
                                        'fenname' => $vv['fenname'],
                                        'ren' => $ren,
                                        'cai' => $cai,
                                        'ji' => $ji,
                                        'fen' => $fen,
                                        'optmoney' => $optmoney
                                    ];
                                    $zhiList[] = $arr;
                                }
                            }
                        }else{
                            $arr = [
                                'qingname' => $qingname,
                                'rate' => $v['rate'],
                                'ratio' => '',
                                'fenname' => '',
                                'ren' => '',
                                'cai' => '',
                                'ji' => '',
                                'fen' => '',
                                'optmoney' => ''
                            ];
                            $zhiList[] = $arr;
                        }
                    }else if($v['key'] == 'jian'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }
                        if($v['resvalue'] == 'chui'){
                            $qingname = '垂直运输费';
                        }else if($v['resvalue'] == 'cuo'){
                            $qingname = '措施费';
                        }else if($v['resvalue'] == 'gong'){
                            $qingname = '管理人员工资';
                        }else if($v['resvalue'] == 'guan'){
                            $qingname = '管理费';
                        }else if($v['resvalue'] == 'yuzhi'){
                            $qingname = '预置表1';
                        }else if($v['resvalue'] == 'yuzhitwo'){
                            $qingname = '预置表2';
                        }else{
                            $qingname = '';
                        }

                        $money = isset($jianArr[$v['resvalue']]) ? $jianArr[$v['resvalue']] : 0;
                        $optmoney = $money * $v['rate'] * $v['ratio'];
                        $arr = [
                            'qingname' => $qingname,
                            'rate' => $v['rate'],
                            'ratio' => '',
                            'fenname' => '',
                            'ren' => '',
                            'cai' => '',
                            'ji' => '',
                            'fen' => '',
                            'optmoney' => $money
                        ];
                        $zhiList[] = $arr;
                    }else if($v['key'] == 'tou'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        $v['ratio'] = empty($v['ratio']) ? 1 : $v['ratio'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }
                        if(substr($v['ratio'], 0 , 1) === '='){
                            $v['ratio'] = maths(substr($v['ratio'],  1));
                        }
                        $money = $engininfo['money'];
                        $optmoney = $money * $v['rate'] * $v['ratio'];
                        $arr = [
                            'qingname' => '投标价金额',
                            'rate' => $v['rate'],
                            'ratio' => '',
                            'fenname' => '',
                            'ren' => '',
                            'cai' => '',
                            'ji' => '',
                            'fen' => '',
                            'optmoney' => $optmoney
                        ];
                        $zhiList[] = $arr;
                    }else if($v['key'] == 'qi'){
                        $v['rate'] = empty($v['rate']) ? 1 : $v['rate'];
                        if(substr($v['rate'], 0 , 1) === '='){
                            $v['rate'] = maths(substr($v['rate'],  1));
                        }

                        $money = 0;
                        if(substr($v['rate'], 0 , 1) === '='){
                            $money += maths(substr($v['rate'],  1));
                        }else{
                            $money += $v['rate'];
                        }
                        if($v['resvalue'] == '1'){
                            $qingname = '其他费用项1';
                        }else if($v['resvalue'] == '2'){
                            $qingname = '其他费用项2';
                        }
                        $arr = [
                            'qingname' => $qingname,
                            'rate' => $v['rate'],
                            'ratio' => '',
                            'fenname' => '',
                            'ren' => '',
                            'cai' => '',
                            'ji' => '',
                            'fen' => '',
                            'optmoney' => $money
                        ];
                        $zhiList[] = $arr;
                    }
                }
            }
            $item['zhi_list'] = $zhiList;


            // 将产值数组存入数组中
            $chanAllList[] = $chan_list;
        }

        foreach ($list as &$item){
            $item['chanfee'] = round($item['chanfee'], 2);
            $item['shoufee'] = round($item['shoufee'], 2);
            $item['zhifee'] = round($item['zhifee'], 2);
            $item['leichan'] = round($item['leichan'], 2);
            $item['leishou'] = round($item['leishou'], 2);
            $item['leizhi'] = round($item['leizhi'], 2);
            $item['dianzhi'] = round($item['dianzhi'], 2);
            $item['dianli'] = round($item['dianli'], 2);
        }


        $data['data'] = $list;
        $data['min_dianzhi'] = search_arr2_min($list, 'dianzhi');

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_huizi(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);

            if(count($list) < 1){
                return outputJson(4009, "请输入成本表信息");
            }

            Db::startTrans();
            try {
                MainHuiziModel::where(['enginid'=>$param['enginid']])->delete();
                foreach ($list as $item){
                    $item['enginid'] = $param['enginid'];
                    MainHuiziModel::insert($item);
                }

                (new MainService())->update_at_main($param['enginid'], 'huizi');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->get('enginid', 0, 'int');
            $data = MainEnginModel::where(['id'=>$enginid])->find();
            if(!$data){
                return outputJson(4009,lang('code_4009'));
            }

            $list = MainHuiziModel::where(['enginid'=>$data['id']])->select()->toArray();

            // 查询前面的数据
            foreach ($list as $k => &$item){
                $checkArr = [];
                foreach ($list as $kk => $v){
                    if($kk < $k){
                        $chanArr = json_decode($v['chan'], true);
                        foreach ($chanArr as $vv){
                            if($vv['key'] == 'qing'){
                                $checkArr['qing'][] = $vv['resvalue'];
                                if(!empty($vv['fenname'])){
                                    foreach ($vv['fenname'] as $vvv){
                                        $checkArr['qing']['children'][] = $vvv['fenname'];
                                    }
                                }
                            }
                            if($vv['key'] == 'cuo'){
                                $checkArr['cuo'][] = $vv['resvalue'];
                            }
                            if($vv['key'] == 'jian'){
                                $checkArr['jian'][] = $vv['resvalue'];
                            }
                            if($vv['key'] == 'tou'){
                                $checkArr['tou'][] = $vv['resvalue'];
                            }
                            if($vv['key'] == 'qi'){
                                $checkArr['qi'][] = $vv['resvalue'];
                            }
                        }
                    }
                }

                $item['checkarr'] = json_encode($checkArr);
            }
            $data['list'] = $list;

            $qinglist = MainQingModel::field('id,qingname')->where(['enginid'=>$data['id']])->select()->toArray();
            foreach ($qinglist as &$item){
                $children = MainQingListModel::where(['enginid'=>$data['id'],'qingid'=>$item['id']])->group('fenname')
                    ->order('id ASC')->column('fenname');
                $children = implode(',', $children);
                $item['children'] = $children;
            }


            $data['qinglist'] = $qinglist;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function search_huizi(Request $request)
    {
        $param = $request->param();
        $param['key'] += 1;
        $jianArr = (new MainService())->get_jianArr($param['enginid']);
        $qingArr = (new MainService())->get_huizi_qingArr($param['enginid']);

        if($param['type'] == 'qing'){
            $qingListArr = MainQingListModel::where(['enginid'=>$param['enginid'],'qingid'=>$param['id']])->field('fenname as enname')->group('fenname')->select()->toArray();
            $data = [];
        }else{
            $data['money'] = 0;
        }

        $list = MainHuiziModel::where(['enginid'=>$param['enginid']])->select()->toArray();

        // 查询前面的数据
        foreach ($list as $k => $item){
            // 获取当月产值的分类的数组 key => value 模式
            $chan_list = (new MainService())->get_chan_list($item['enginid'], $item['chan'], $qingArr,$jianArr);

            if($param['type'] == 'qing' && $k < ($param['key'] - 1)){
                foreach ($qingListArr as $v){
                    if(isset($chan_list[$v['enname'].'_ren'.$param['id']])){
                        $ren = $chan_list[$v['enname'].'_ren'.$param['id']];
                        $cai = $chan_list[$v['enname'].'_cai'.$param['id']];
                        $ji = $chan_list[$v['enname'].'_ji'.$param['id']];
                        $fen = $chan_list[$v['enname'].'_fen'.$param['id']];
                        $money = $ren + $cai + $ji + $fen;
                        if(isset($data[$v['enname']])){
                            $data[$v['enname']]['ren'] += $ren;
                            $data[$v['enname']]['cai'] += $cai;
                            $data[$v['enname']]['ji'] += $ji;
                            $data[$v['enname']]['fen'] += $fen;
                            $data[$v['enname']]['money'] += $money;
                        }else{
                            $data[$v['enname']] = [
                                'name' => $v['enname'],
                                'ren' => $ren,
                                'cai' => $cai,
                                'ji' => $ji,
                                'fen' => $fen,
                                'money' => $money,
                            ];
                        }
                    }
                }
            }

            if($param['type'] == 'chui' && $k < $param['key'] - 1 && isset($chan_list['chui'])){
                $data['money'] += $chan_list['chui'];
            }
            if($param['type'] == 'cuo' && $k < $param['key'] - 1 && isset($chan_list['cuo'])){
                $data['money'] += $chan_list['cuo'];
            }
            if($param['type'] == 'guan' && $k < $param['key'] - 1 && isset($chan_list['guan'])){
                $data['money'] += $chan_list['guan'];
            }
            if($param['type'] == 'gong' && $k < $param['key'] - 1 && isset($chan_list['gong'])){
                $data['money'] += $chan_list['gong'];
            }
            if($param['type'] == 'yuzhi' && $k < $param['key'] - 1 && isset($chan_list['yuzhi'])){
                $data['money'] += $chan_list['yuzhi'];
            }
            if($param['type'] == 'yuzhitwo' && $k < $param['key'] - 1 && isset($chan_list['yuzhitwo'])){
                $data['money'] += $chan_list['yuzhitwo'];
            }
            if($param['type'] == 'tou' && $k < $param['key'] - 1 && isset($chan_list['tou'])){
                $data['money'] += $chan_list['tou'];
            }
            if($param['type'] == 'qi' && $k < $param['key'] - 1){
                $data['money'] += $chan_list[$param['id']];
            }
        }
        if($param['type'] == 'qing'){
            $name = MainQingModel::where('id',$param['id'])->value('qingname');
            $money = 0;
            $money += array_sum(array_column($data,'ren'));
            $money += array_sum(array_column($data,'cai'));
            $money += array_sum(array_column($data,'ji'));
            $money += array_sum(array_column($data,'fen'));
            $data = ['name'=>$name,'moeny'=>$money,'list'=>array_values($data)];
        }else{
            if($param['type'] == 'chui'){
                $data['name'] = '垂直运输费';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'cuo'){
                $data['name'] = '措施费';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'gong'){
                $data['name'] = '管理人员工资';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'guan'){
                $data['name'] = '管理费';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'yuzhi'){
                $data['name'] = '预置表1';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'yuzhitwo'){
                $data['name'] = '预置表2';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'tou'){
                $data['name'] = '投标价金额';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'qi' && $param['id'] == 1){
                $data['name'] = '其他费用项1';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
            if($param['type'] == 'qi' && $param['id'] == 2){
                $data['name'] = '其他费用项2';
                $data['money'] = isset($data['money']) ? $data['money'] : 0;
            }
        }
        return outputJson(2000,lang('code_2000'),$data);
    }

    //总价汇总表
    public function list_huishu(Request $request)
    {
        $param = $request->post();
        $engininfo = MainEnginModel::where(['id'=>$param['enginid']])->find();
        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'huishu');

        $list = [];
        $qingArr = (new MainService())->get_qingArr($param['enginid']);
        $tujian = ['xuhao'=>1,'name'=>'土建工程', 'toufee'=>0, 'yufee'=>0, 'chanfee'=>0,'mian'=>0];
        $tujian['mian'] = $engininfo['mian'];
        $tujiansom = [];
        $xuhao = 1;
        foreach ($qingArr as $k=>$v){
            $qing_data = MainQingModel::where(['id'=>$k])->find();
            $money = MainQingListModel::where(['qingid'=>$k])->sum('money');
            $tujiansom[] = ['xuhao'=>'1.'.$xuhao,'name'=>$qing_data['qingname'], 'toufee'=>0, 'yufee'=>0, 'chanfee'=>$money,'mian'=>$qing_data['area']];
            $tujian['chanfee'] += $money;
            $xuhao++;
        }
        $list[] = $tujian;
        foreach ($tujiansom as $k=>$v){
            $list[] = $v;
        }


        $noshui_chengfee = $tujian['chanfee'];

        $jianArr = (new MainService())->get_jianArr($param['enginid']);
        $shulist = MainHuishuModel::where(['enginid'=>$param['enginid']])->select()->toArray();
        $xuhao = 2;
        foreach ($shulist as $key=>&$item){
            $item['xuhao'] = $xuhao;
            $item['toufee'] = 0;
            $item['yufee'] = 0;
            $_chanfee = (new MainService())->get_huishu_chan($item['enginid'], $item['chan'], $qingArr,$jianArr);
            if($item['name'] == '项目管理费成本'){
                $_chanfee = round($_chanfee / 2,2);
            }
            $item['chanfee'] = $_chanfee;
            $noshui_chengfee += $_chanfee;
            $list[] = $item;
            $xuhao++;
        }

        $list[] = ['xuhao'=>$xuhao,'name'=>'不含税工程造价', 'toufee'=>$engininfo['no_money'],'yufee'=>$engininfo['budget_no_money'],'chanfee'=>$noshui_chengfee];
        $xuhao++;
        $list[] = ['xuhao'=>$xuhao,'name'=>'税率', 'toufee'=>$engininfo['rate'],'yufee'=>$engininfo['budget_rate'],'chanfee'=>$engininfo['rate']];
        $xuhao++;
        $list[] = ['xuhao'=>$xuhao,'name'=>'税金', 'toufee'=>$engininfo['rate_money'],'yufee'=>$engininfo['budget_rate_money'],'chanfee'=>$engininfo['rate_money']];
        $xuhao++;

        if(empty($noshui_chengfee)) $noshui_chengfee = 0;
        if(empty($engininfo['rate_money'])) $engininfo['rate_money'] = 0;
        $hanshui_chengfee = ($noshui_chengfee + $engininfo['rate_money']);
        $list[] = ['xuhao'=>$xuhao,'name'=>'含税工程造价', 'toufee'=>$engininfo['money'],'yufee'=>$engininfo['budget_money'],'chanfee'=>$hanshui_chengfee];
        $xuhao++;

        foreach ($list as &$vvv){
            if(isset($vvv['mian'])){
                $vvv['gerate'] = $hanshui_chengfee != 0 ? (round($vvv['chanfee']/$hanshui_chengfee*100, 2)).'%' : 0;
                $vvv['toudan'] = $vvv['mian'] != 0 ? (round($vvv['toufee']/$vvv['mian'], 2)) : 0;
                $vvv['yudan'] = $vvv['mian'] != 0 ? (round($vvv['yufee']/$vvv['mian'], 2)) : 0;
                $vvv['chandan'] = $vvv['mian'] != 0 ? (round($vvv['chanfee']/$vvv['mian'], 2)) : 0;
                $vvv['jianarea'] = $vvv['mian'];
            }else{
                if(empty($vvv['chanfee'])) $vvv['chanfee'] = 0;
                if(empty($vvv['toufee'])) $vvv['toufee'] = 0;
                if(empty($vvv['yufee'])) $vvv['yufee'] = 0;
                if(empty($vvv['chanfee'])) $vvv['chanfee'] = 0;
                $vvv['gerate'] = $hanshui_chengfee != 0 ? (round($vvv['chanfee']/$hanshui_chengfee*100, 2)).'%' : 0;
                $vvv['toudan'] = $engininfo['mian'] != 0 ? (round($vvv['toufee']/$engininfo['mian'], 2)) : 0;
                $vvv['yudan'] = $engininfo['mian'] != 0 ? (round($vvv['yufee']/$engininfo['mian'], 2)) : 0;
                $vvv['chandan'] = $engininfo['mian'] != 0 ? (round($vvv['chanfee']/$engininfo['mian'], 2)) : 0;
                $vvv['jianarea'] = $engininfo['mian'];
            }
        }

        if(empty($engininfo['money'])) $engininfo['money'] = 0;
        if(empty($engininfo['budget_money'])) $engininfo['budget_money'] = 0;
        $list[] = [
            'xuhao'=>$xuhao,
            'name'=>'成本与投标价利润金额',
            'toufee'=>$engininfo['money'] - $hanshui_chengfee,
            'yufee'=>$engininfo['budget_money'] - $hanshui_chengfee,
        ];
        $xuhao++;
        $list[] = [
            'xuhao'=>$xuhao,
            'name'=>'利润率',
            'toufee'=> $engininfo['money'] != 0 ? (round(($engininfo['money'] - $hanshui_chengfee)/$engininfo['money']*100, 2)).'%' : 0,
            'yufee'=> $engininfo['budget_money'] != 0 ? (round(($engininfo['budget_money'] - $hanshui_chengfee)/$engininfo['budget_money']*100, 2)).'%' : 0,
        ];


        foreach ($list as &$item){
            $item['chanfee'] = isset($item['chanfee']) ? $item['chanfee'] : '';
            $item['toufee'] = isset($item['toufee']) ? $item['toufee'] : '';
            $item['yufee'] = isset($item['yufee']) ? $item['yufee'] : '';
            $item['toudan'] = isset($item['toudan']) ? $item['toudan'] : '';
            $item['yudan'] = isset($item['yudan']) ? $item['yudan'] : '';
            $item['chandan'] = isset($item['chandan']) ? $item['chandan'] : '';

            $item['toufee'] = round($item['toufee'], 2);
            $item['yufee'] = round($item['yufee'], 2);
            $item['chanfee'] = round($item['chanfee'], 2);
            $item['toudan'] = round($item['toudan'], 2);
            $item['yudan'] = round($item['yudan'], 2);
            $item['chandan'] = round($item['chandan'], 2);
        }


        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_huishu(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);

            if(count($list) < 1){
                return outputJson(4009, "请输入信息");
            }

            Db::startTrans();
            try {
                MainHuishuModel::where(['enginid'=>$param['enginid']])->delete();
                foreach ($list as $item){
                    $item['enginid'] = $param['enginid'];
                    MainHuishuModel::insert($item);
                }

                (new MainService())->update_at_main($param['enginid'], 'huishu');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->get('enginid', 0, 'int');
            $data = MainEnginModel::where(['id'=>$enginid])->find();
            if(!$data){
                return outputJson(4009,lang('code_4009'));
            }

            $list = MainHuishuModel::where(['enginid'=>$data['id']])->select()->toArray();
            $data['list'] = $list;

            $otherlist = [];
            $otherlist['chui'] = MainJianEnginChuiModel::where(['enginid'=>$data['id'],'pid'=>0])->sum('allfee');
            $otherlist['cuo'] = MainJianEnginCuoModel::where(['enginid'=>$data['id'],'pid'=>0])->sum('heprice');

            $otherlist['gong'] = MainJianEnginGongModel::where(['enginid'=>$data['id'],'pid'=>0])->sum('hefee');
            $otherlist['gong'] = $otherlist['gong'] / 2;
            $otherlist['guan'] = MainJianEnginGuanModel::where(['enginid'=>$data['id'],'pid'=>0])->sum('heprice');
            $otherlist['guan'] = $otherlist['guan'] / 2;

            $otherlist['yuzhi'] = MainJianEnginYuoneModel::where(['enginid'=>$data['id'],'pid'=>0])->sum('heprice');
            $otherlist['yuzhitwo'] = MainJianEnginYutwoModel::where(['enginid'=>$data['id'],'pid'=>0])->sum('heprice');
            $otherlist['money'] = empty($data['money']) ? 0 : $data['money'];
            $otherlist['dianzhi'] = 0;
            $list = MainHuiziModel::where(['enginid'=>$data['id']])->select()->toArray();
            $jianArr = (new MainService())->get_jianArr($data['id']);
            $qingArr = (new MainService())->get_huizi_qingArr($data['id']);
            foreach ($list as $key=>&$item){
                $item['chanfee'] = (new MainService())->get_huizi_chan($item['enginid'], $item['chan'], $qingArr,$jianArr);
                $item['shoufee'] = (new MainService())->get_huizi_chan($item['enginid'], $item['shou'], $qingArr,$jianArr);
                $item['zhifee'] = $item['chanfee'] * $item['zhirate']/100;

                if($key == 0){
                    $item['leishou'] = $item['shoufee'];
                }else{
                    $item['leishou'] = $item['shoufee'] + $list[$key-1]['leishou'];
                }
                if($key == 0){
                    $item['leizhi'] = $item['zhifee'];
                }else{
                    $item['leizhi'] = $item['zhifee'] + $list[$key-1]['leizhi'];
                }
                $item['dianzhi'] = $item['leizhi'] - $item['leishou'];
                $item['dianli'] = -($item['dianzhi'] * $item['dianrate'] / 100);
                $otherlist['dianzhi'] += $item['dianli'];
            }
            $otherlist['dianzhi'] = empty($otherlist['dianzhi']) ? 0 : round($otherlist['dianzhi'],2);
            $data['otherlist'] = $otherlist;


            $qinglist = MainQingModel::field('id,qingname')->where(['enginid'=>$data['id']])->select()->toArray();
            foreach ($qinglist as &$v){
                $money = MainQingListModel::where(['qingid'=>$v['id']])->sum('money');
                $v['money'] = $money;
            }
            $data['qinglist'] = $qinglist;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    //单方造价表
    public function list_huizao(Request $request)
    {
        $param = $request->post();

        $engininfo = MainEnginModel::where(['id'=>$param['enginid']])->find();
        $data['tit'] = (new MainService())->get_maineditshi($param['enginid'],'huizao');

        $typeArr = (new MainService())->get_huizao_type();
        $basalfee = (new MainService())->get_huizao_basalfee($param['enginid']);

        $listArr[0] = [
            'xuhao'=>1,
            'mian'=>$engininfo['mian'],
            'name'=>'土建工程',
            'chengfee'=>0,
            'zaofee'=>0,
            'islight'=>0,
        ];
        foreach ($typeArr as $key=>$fenname){
            $_item = [
                'xuhao'=>'1.'.$key,
                'mian'=>$engininfo['mian'],
                'name'=>$fenname,
                'chengfee'=>0,
                'islight'=>1,
                'zaofee'=>0,
            ];
            $list = MainHuizaoModel::where(['enginid'=>$param['enginid'],'type'=>$key])->select()->toArray();

            foreach ($list as $kk=>&$item){
                $xuhao = $kk + 1;
                $item['xuhao'] = $_item['xuhao'].'.'.$xuhao;
                $item['mian'] = $engininfo['mian'];
                $item['chengfee'] = (new MainService())->get_huizao_chengfee($item, $basalfee);
                $item['zaofee'] = $item['mian'] != 0 ? $item['chengfee'] / $item['mian'] : 0;
                $_item['chengfee'] += $item['chengfee'];
                $_item['zaofee'] += $item['zaofee'];
                $listArr[0]['chengfee'] += $item['chengfee'];
                $listArr[0]['zaofee'] += $item['zaofee'];
            }

            $listArr[] = $_item;
            foreach ($list as $vvv){
                $vvv['islight'] = 0;
                $listArr[] = $vvv;
            }
        }




        $qingArr = (new MainService())->get_qingArr($param['enginid']);
        $jianArr = (new MainService())->get_jianArr($param['enginid']);
        $shulist = MainHuishuModel::where(['enginid'=>$param['enginid']])->select()->toArray();
        $qixuhao = 2;
        $qiallchengfee = 0;
        foreach ($shulist as $item){
            $qiarr = [];
            $qiarr['name'] = $item['name'];
            $qiarr['mian'] = $engininfo['mian'];
            $qiarr['xuhao'] = $qixuhao;
            $qixuhao++;
            $qiarr['islight'] = 0;
            $qiarr['chengfee'] = (new MainService())->get_huishu_chan($item['enginid'], $item['chan'], $qingArr,$jianArr);
            if($item['name'] == '项目管理费成本'){
                $qiarr['chengfee'] = round($qiarr['chengfee'] / 2,2);
            }
            $qiallchengfee += $qiarr['chengfee'];
            $qiarr['zaofee'] = $qiarr['mian'] != 0 ? $qiarr['chengfee'] / $qiarr['mian'] : 0;
            $listArr[] = $qiarr;
        }


        $nohanrateChengfee = $listArr[0]['chengfee'] + $qiallchengfee;
        $nohanrate = [
            'name' => '不含税工程造价',
            'xuhao' => $qixuhao,
            'mian' => $engininfo['mian'],
            'islight' => 0,
            'chengfee' => $nohanrateChengfee,
            'zaofee' => $qiarr['mian'] != 0 ? $nohanrateChengfee / $qiarr['mian'] : 0,
        ];
        $qixuhao++;
        $listArr[] = $nohanrate;


        $shuijin = [
            'name' => '税金',
            'xuhao' => $qixuhao,
            'mian' => $engininfo['mian'],
            'islight' => 0,
            'chengfee' => $engininfo['rate_money'],
            'zaofee' => $qiarr['mian'] != 0 ? $engininfo['rate_money'] / $qiarr['mian'] : 0,
        ];
        $qixuhao++;
        $listArr[] = $shuijin;

        $hanshuichengben = [
            'name' => '含税成本价',
            'xuhao' => $qixuhao,
            'mian' => $engininfo['mian'],
            'islight' => 0,
            'chengfee' => $nohanrateChengfee+$engininfo['rate_money'],
            'zaofee' => $qiarr['mian'] != 0 ? ($nohanrateChengfee+$engininfo['rate_money']) / $qiarr['mian'] : 0,
        ];
        $qixuhao++;
        $listArr[] = $hanshuichengben;

        $yu_hanfee = $engininfo['money'];
        if(empty($yu_hanfee)) $yu_hanfee = 0;
        $hanshuiyusuan = [
            'name' => '含税投标价',
            'xuhao' => $qixuhao,
            'mian' => $engininfo['mian'],
            'islight' => 0,
            'chengfee' => $yu_hanfee,
            'zaofee' => $qiarr['mian'] != 0 ? $yu_hanfee / $qiarr['mian'] : 0,
        ];
        $qixuhao++;
        $listArr[] = $hanshuiyusuan;

        if(empty($engininfo['rate'])) $engininfo['rate'] = 0;
        if(empty($nohanrateChengfee)) $nohanrateChengfee = 0;
        if(empty($yu_hanfee)) $yu_hanfee = 0;
        $lirun = [
            'name' => '成本与投标价利润金额',
            'xuhao' => $qixuhao,
            'mian' => $engininfo['mian'],
            'islight' => 0,
            'chengfee' => $yu_hanfee - ($nohanrateChengfee+($nohanrateChengfee * $engininfo['rate'] / 100)),
            'zaofee' => $qiarr['mian'] != 0 ? ($yu_hanfee - ($nohanrateChengfee+$engininfo['rate_money'])) / $qiarr['mian'] : 0,
        ];
        $qixuhao++;
        $listArr[] = $lirun;

        if(empty($yu_hanfee )) $yu_hanfee = 0;
        if(empty($engininfo['rate_money'])) $engininfo['rate_money'] = 0;
        if(empty($nohanrateChengfee)) $nohanrateChengfee = 0;
        $lirunrate = [
            'name' => '利润率',
            'xuhao' => $qixuhao,
            'mian' => $engininfo['mian'],
            'islight' => 0,
            'chengfee' => $yu_hanfee != 0 ?($yu_hanfee - ($nohanrateChengfee+($nohanrateChengfee * $engininfo['rate'] / 100))) / $yu_hanfee * 100 : 0,
            'zaofee' => $qiarr['mian'] != 0 ? ($yu_hanfee != 0 ? ($yu_hanfee - ($nohanrateChengfee+$engininfo['hui_ratefee'])) / $yu_hanfee : 0) / $qiarr['mian'] : 0,
        ];
        $qixuhao++;
        $listArr[] = $lirunrate;

        foreach ($listArr as &$item){
            $item['chengfee'] = round($item['chengfee'], 2);
            $item['zaofee'] = round($item['zaofee'], 2);
        }

        $data['data'] = $listArr;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_huizao(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);

            if(count($list) < 1){
                return outputJson(4009, "请输入表信息");
            }

            Db::startTrans();
            try {
                MainHuizaoModel::where(['enginid'=>$param['enginid']])->delete();
                foreach ($list as $item){
                    $item['enginid'] = $param['enginid'];
                    MainHuizaoModel::insert($item);
                }

                (new MainService())->update_at_main($param['enginid'], 'huizao');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $enginid = $request->get('enginid', 0, 'int');
            $data = MainEnginModel::where(['id'=>$enginid])->find();
            if(!$data){
                return outputJson(4009,lang('code_4009'));
            }

            $data['listtype1'] = MainHuizaoModel::where(['enginid'=>$data['id'],'type'=>1])->select()->toArray();
            $data['listtype2'] = MainHuizaoModel::where(['enginid'=>$data['id'],'type'=>2])->select()->toArray();
            $data['listtype3'] = MainHuizaoModel::where(['enginid'=>$data['id'],'type'=>3])->select()->toArray();
            $data['listtype4'] = MainHuizaoModel::where(['enginid'=>$data['id'],'type'=>4])->select()->toArray();

            $basallist = MainBasalModel::field('fenname')->where(['enginid'=>$data['id']])->group('fenname')
                ->order('id ASC')->column('fenname');
            $basalarr = [];
            foreach ($basallist as $v){
                $item['fenname'] = $v;
                $item['renfee_cur'] = MainQingListModel::where(['enginid'=>$data['id']])->where('fenname',$v)->sum('renfee_cur');
                $item['caifee_cur'] = MainQingListModel::where(['enginid'=>$data['id']])->where('fenname',$v)->sum('caifee_cur');
                $item['jifee_cur'] = MainQingListModel::where(['enginid'=>$data['id']])->where('fenname',$v)->sum('jifee_cur');
                $item['fenfee_cur'] = MainQingListModel::where(['enginid'=>$data['id']])->where('fenname',$v)->sum('fenfee_cur');
                $basalarr[] = $item;
            }
            $data['basallist'] = $basallist;
            $data['basalarr'] = $basalarr;


            // 初始化金额
            $listtype1 = $data['listtype1'];
            foreach ($listtype1 as &$type){
                $type['money'] = 0;
                $cheng = json_decode($type['cheng'],true);
                foreach($cheng as $k => $c){
                    $cArr = array_filter(explode(',',$c));
                    foreach ($cArr as $v){
                        foreach ($basalarr as $item){
                            if($item['fenname'] == $v){
                                if($k == 1){
                                    $type['money'] += $item['renfee_cur'];
                                }
                                if($k == 2){
                                    $type['money'] += $item['fenfee_cur'];
                                }
                                if($k == 3){
                                    $type['money'] += $item['jifee_cur'];
                                }
                                if($k == 4){
                                    $type['money'] += $item['caifee_cur'];
                                }
                            }
                        }
                    }
                }
            }
            $data['listtype1'] = $listtype1;
            unset($type);

            $listtype2 = $data['listtype2'];
            foreach ($listtype2 as &$type){
                $type['money'] = 0;
                $cheng = json_decode($type['cheng'],true);
                foreach($cheng as $k => $c){
                    $cArr = array_filter(explode(',',$c));
                    foreach ($cArr as $v){
                        foreach ($basalarr as $item){
                            if($item['fenname'] == $v){
                                if($k == 1){
                                    $type['money'] += $item['renfee_cur'];
                                }
                                if($k == 2){
                                    $type['money'] += $item['fenfee_cur'];
                                }
                                if($k == 3){
                                    $type['money'] += $item['jifee_cur'];
                                }
                                if($k == 4){
                                    $type['money'] += $item['caifee_cur'];
                                }
                            }
                        }
                    }
                }
            }
            $data['listtype2'] = $listtype2;

            $listtype3 = $data['listtype3'];
            foreach ($listtype3 as &$type){
                $type['money'] = 0;
                $cheng = json_decode($type['cheng'],true);
                foreach($cheng as $k => $c){
                    $cArr = array_filter(explode(',',$c));
                    foreach ($cArr as $v){
                        foreach ($basalarr as $item){
                            if($item['fenname'] == $v){
                                if($k == 1){
                                    $type['money'] += $item['renfee_cur'];
                                }
                                if($k == 2){
                                    $type['money'] += $item['fenfee_cur'];
                                }
                                if($k == 3){
                                    $type['money'] += $item['jifee_cur'];
                                }
                                if($k == 4){
                                    $type['money'] += $item['caifee_cur'];
                                }
                            }
                        }
                    }
                }
            }
            $data['listtype3'] = $listtype3;

            $listtype4 = $data['listtype4'];
            foreach ($listtype4 as &$type){
                $type['money'] = 0;
                $cheng = json_decode($type['cheng'],true);
                foreach($cheng as $k => $c){
                    $cArr = array_filter(explode(',',$c));
                    foreach ($cArr as $v){
                        foreach ($basalarr as $item){
                            if($item['fenname'] == $v){
                                if($k == 1){
                                    $type['money'] += $item['renfee_cur'];
                                }
                                if($k == 2){
                                    $type['money'] += $item['fenfee_cur'];
                                }
                                if($k == 3){
                                    $type['money'] += $item['jifee_cur'];
                                }
                                if($k == 4){
                                    $type['money'] += $item['caifee_cur'];
                                }
                            }
                        }
                    }
                }
            }
            $data['listtype4'] = $listtype4;


            $list = MainBasalModel::field('fenname as enname')->where(['enginid'=>$data['id']])->group('fenname')
                ->order('id ASC')->select()->toArray();
            foreach ($list as &$item){
                $item['fee_ren'] = MainBasalModel::where(['enginid'=>$data['id']])->where('fenname',$item['enname'])->sum('renfee');
                $item['fee_cai'] = MainBasalModel::where(['enginid'=>$data['id']])->where('fenname',$item['enname'])->sum('caifee');
                $item['fee_ji'] = MainBasalModel::where(['enginid'=>$data['id']])->where('fenname',$item['enname'])->sum('jifee');
                $item['fee_zhuan'] = MainBasalModel::where(['enginid'=>$data['id']])->where('fenname',$item['enname'])->sum('fenfee');
            }
            $data['list'] = $list;

            return outputJson(2000,lang('code_2000'),$data);
        }
    }






    public function getgong(){
        $file = request()->file("file");
        $move_path = 'mainfile';
        $fileInfo = $file->getInfo();
        $info = $file->validate(['size'=>52428800, 'ext'=>'xls,xlsx'])->move($move_path);
        $data = [];
        if($info){
            $filename = 'mainfile/'.str_replace('\\', '/', $info->getSaveName());
            $ext = $info->getExtension();
            $data = $this->getGongArr($filename, $ext);
            $qingname = str_replace('.'.$ext,'',$fileInfo['name']);
        }else{
            return outputJson(4000, "请上传正确的excel");
        }
        if(!$data || !is_array($data) || count($data) < 1){
            return outputJson(4000, "未获取到有效数据");
        }
        $list['data'] = $data;
        $list['filename'] = $filename;
        $list['qingname'] = $qingname;
        $list['ext'] = $ext;
        return outputJson(2000,lang('code_2000'), $list);
    }
    public function getfile(Request $request){
        $param = $request->post();
        $data = $this->getData($param['filename'], $param['ext'], $param['sheetid']);
        if(file_exists($param['filename'])){
            unlink($param['filename']);
        }
        if(!$data || !is_array($data) || count($data) < 1){
            return outputJson(4000, "未获取到有效数据");
        }


        //获取标识字段是否包含有（项目编码， 工程名称， 项目特征描述）  -  计量单位 工程量
        $qingArr = [];
        $encodeField = '';
        $ennameField = '';
        $enfeatField = '';
        $enunitField = '';
        $enwordField = '';
        foreach ($data as $k=>$v){
            if((in_array('项目编码', $v) || in_array('编码', $v)) &&
                in_array('工程名称', $v) &&
                in_array('项目特征描述', $v)){
                $qingArr = $v;
                foreach ($qingArr as $kk=>$vv){
                    $vv = str_replace(  "\n", '',$vv);
                    if($vv == '项目编码' || $vv == '编码'){
                        $encodeField = $kk;
                        if($vv == '编码'){
                            $qingArr[$kk] = '项目编码';
                        }
                    }
                    if($vv == '工程名称'){
                        $ennameField = $kk;
                    }
                    if($vv == '项目特征描述'){
                        $enfeatField = $kk;
                    }
                    if($vv == '计量单位' || $vv == '单位'){
                        $enunitField = $kk;
                        if($vv == '单位'){
                            $qingArr[$kk] = '计量单位';
                        }
                    }
                    if($vv == '工程量'){
                        $enwordField = $kk;
                    }
                    $qingArr[$kk] = $vv;
                }
                break;
            }
        }
        if(!$qingArr || !is_array($qingArr) || count($qingArr) < 1){
            return outputJson(4000, "未获取到有效数据");
        }

//        if(!empty($encodeField)){
//            foreach ($data as $kkkk=>$vvvv){
//                if(isset($vvvv[$enwordField]) && !empty($vvvv[$enwordField])){
//                    $one = substr($vvvv[$enwordField], 0 , 1);
//                    if($one === '='){
//                        $data[$kkkk][$enwordField] = round(maths(substr($vvvv[$enwordField],  1)), 2);
//                    }
//                }
//            }
//        }

        $zimu = '';
        foreach ($data as $key=>&$item){
            foreach ($item as $kk=>$vv){
                $item[$kk] = str_replace(  "\n", '<br/>',$vv);
            }


            $hang = '无效行';
            if(!empty($item[$ennameField])){
                if(!empty($item[$encodeField])){
                    if(empty($item[$enunitField])){
                        $hang = '分部行';
                    }else{
                        if(str_replace("<br/>",'',$item[$enunitField]) != '计量单位'){
                            $hang = '清单行';
                        }
                        // 如果是数字
                        if(is_numeric($item[$enunitField])){
                            $hang = '分部行';
                        }
                    }
                }else{
                    if(empty($item[$enunitField])){
                        $hang = '分部行';
                    }else{
                        if(str_replace("<br/>",'',$item[$enunitField]) != '计量单位'){
                            $hang = '清单行';
                        }
                        // 如果是数字
                        if(is_numeric($item[$enunitField])){
                            $hang = '分部行';
                        }
                    }

                    $kong = true;
                    foreach ($item as $kk=>$vv){
                        if($kk == $encodeField || $kk == $enfeatField || $kk == $enunitField || $kk == $enwordField){
                            if(!empty($vv)){
                                $kong = false;
                            }
                        }
                    }
                    if($kong){
                        if(strpos($item[$ennameField],'合计') !== false){
                            $hang = '无效行';
                        }else{
                            $hang = '分部行';
                        }
                    }
                }
            }

            if($hang =='分部行' ){
                if($key > 0){
                    if($data[$key-1]['hang'] == '分部行'){
                        $hang = '子分部行';
                    }
                    if($data[$key-1]['hang'] == '子分部行'){
                        if(!isset($data[$key-2]['hang']) || ($data[$key-2]['hang'] != '子分部行' && $data[$key-2]['hang'] != '分部行')){
                            $data[$key-1]['hang'] = '分部行';
                        }
                        $hang = '子分部行';
                    }

                    if($hang == '分部行'){
                        if($zimu == '子分部行'){
                            $hang = '子分部行';
                        }
                    }
                }
            }

            if($hang == '子分部行'){
                $zimu = '子分部行';
            }
            if($hang == '分部行'){
                $zimu = '';
            }
            $item['hang'] = $hang;
        }

        $list['data'] = $data;
        $list['qingArr'] = $qingArr;
        $list['defield'] = [$encodeField,$ennameField,$enfeatField,$enunitField,$enwordField];
        return outputJson(2000,lang('code_2000'), $list);
    }
    public function getFileData(Request $request){
        $param = $request->post();
        $data = $this->getData($param['filename'], $param['ext'], $param['sheetid']);
        if(file_exists($param['filename'])){
            unlink($param['filename']);
        }
        if(!$data || !is_array($data) || count($data) < 1){
            return outputJson(4000, "未获取到有效数据");
        }

        //获取标识字段是否包含有（项目编码， 工程名称， 项目特征描述）  -  计量单位 工程量
        $qingArr = [];
        $nameField = '';
        $guigeField = '';
        $valunitField = '';
        $contentField = '';
        $priceField = '';
        $explainField = '';
        foreach ($data as $k=>$v){
            if(in_array('工程名称', $v) || in_array('品牌', $v)){
                $qingArr = $v;
                foreach ($qingArr as $kk=>$vv){
                    $vv = str_replace(  "\n", '',$vv);
                    if($vv == '工程名称'){
                        $nameField = $kk;
                    }
                    if($vv == '项目特征描述'){
                        $guigeField = $kk;
                    }
                    if($vv == '计量单位' || $vv == '单位'){
                        $valunitField = $kk;
                        if($vv == '单位'){
                            $qingArr[$kk] = '计量单位';
                        }
                    }
                    if($vv == '含量'){
                        $contentField = $kk;
                    }
                    if($vv == '单价' || $vv == '不含税价格' || $vv == '不含税单价'){
                        $priceField = $kk;
                    }
                    if($vv == '备注'){
                        $explainField = $kk;
                    }
                    $qingArr[$kk] = $vv;
                }
                break;
            }
        }

        $list = [];
        foreach ($data as $item){
            $exists = 0;
            foreach($item as $vv){
                if(!empty($vv)){
                    $exists = 1;
                    break;
                }
            }
            if($exists == 1){
                $list[] = $item;
            }
        }



        $list['data'] = $list;
        $list['qingArr'] = $qingArr;
        $list['defield'] = [$nameField,$guigeField,$valunitField,$contentField,$priceField,$explainField];
        return outputJson(2000,lang('code_2000'), $list);
    }
    public function getGongArr($filename, $exts){
        require_once '../extend/phpoffice/PHPExcel/PHPExcel.php';
        $PHPExcel = new \PHPExcel();
        if ($exts == 'xls') {
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel5.php';
            $PHPReader = new \PHPExcel_Reader_Excel5();
            $PHPExcel = $PHPReader->load($filename);
        } else if ($exts == 'xlsx') {
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel2007.php';
            $PHPReader = new \PHPExcel_Reader_Excel2007();
//            $PHPExcel = $PHPReader->loadSmall($filename);
            $PHPExcel = $PHPReader->load($filename);
        }
        return $PHPExcel->getSheetNames();
    }
    public function getData($filename, $exts, $sheetid){
        require_once '../extend/phpoffice/PHPExcel/PHPExcel.php';
        $PHPExcel = new \PHPExcel();

        if ($exts == 'xls') {
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel5.php';
            $PHPReader = new \PHPExcel_Reader_Excel5();
        } else if ($exts == 'xlsx') {
            require_once '../extend/phpoffice/PHPExcel/PHPExcel/Reader/Excel2007.php';
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        }

        //载入文件
        $PHPExcel = $PHPReader->load($filename);

        $data = $PHPExcel->getSheet($sheetid)->toArray();
        return $data;

//        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
//        $currentSheet = $PHPExcel->getSheet($sheetid);
//        //获取总列数
//        $allColumn = $currentSheet->getHighestColumn();
//        //获取总行数
//        $allRow = $currentSheet->getHighestRow();
//        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
//        for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
//            //从哪列开始，A表示第一列
//            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
//                //数据坐标
//                $address = $currentColumn . $currentRow;
//                //读取到的数据，保存到数组$data中
//                $cell = $currentSheet->getCell($address)->getValue();
//                if ($cell instanceof PHPExcel_RichText) {
//                    $cell = $cell->__toString();
//                }
//                $data[$currentRow - 1][$currentColumn] = $cell;
//                if($currentColumn == 'AA'){
//                    break;
//                }
//            }
//        }
        return $data;
    }
}
